根据多个 ID 排序 MySQL 查询?
为此,使用 ORDER BY FIELD()。我们首先创建一个表 -
mysql> create table DemoTable( ClientId varchar(40), ClientName varchar(40) ); Query OK, 0 rows affected (0.55 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('987_John','John'); Query OK, 1 row affected (0.33 sec) mysql> insert into DemoTable values('1000_Sam','Sam'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('777_Carol','Carol'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2000_Bob','Bob'); Query OK, 1 row affected (0.20 sec)
使用 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)
广告