为此,请使用ORDER BY FIELD()
。让我们首先创建一个表-
mysql> create table DemoTable( ClientId varchar(40), ClientName varchar(40) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('987_John','John'); mysql> insert into DemoTable values('1000_Sam','Sam'); mysql> insert into DemoTable values('777_Carol','Carol'); mysql> insert into DemoTable values('2000_Bob','Bob');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+------------+ | ClientId | ClientName | +-----------+------------+ | 987_John | John | | 1000_Sam | Sam | | 777_Carol | Carol | | 2000_Bob | Bob | +-----------+------------+ 4 rows in set (0.00 sec)
以下是按多个ID排序MySQL查询的查询-
mysql> select *from DemoTable order by field(ClientId,'1000_Sam','2000_Bob','777_Carol','987_John');
这将产生以下输出-
+-----------+------------+ | ClientId | ClientName | +-----------+------------+ | 1000_Sam | Sam | | 2000_Bob | Bob | | 777_Carol | Carol | | 987_John | John | +-----------+------------+ 4 rows in set (0.04 sec)