如何按照 IN 子句所给定的顺序获取 MySQL 查询结果?
为此,你可以结合使用 IN() 和 ORDER BY FIELD()。我们首先创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) ); Query OK, 0 rows affected (0.64 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable(FirstName) values('Chris'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(FirstName) values('Robert'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable(FirstName) values('Mike'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(FirstName) values('Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(FirstName) values('Carol'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(FirstName) values('David'); Query OK, 1 row affected (0.42 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将生成以下输出 −
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | Chris | | 2 | Robert | | 3 | Mike | | 4 | Sam | | 5 | Carol | | 6 | David | +----+-----------+ 6 rows in set (0.00 sec)
以下是按 IN 子句所给定的顺序获取查询结果的方法。
mysql> select FirstName from DemoTable where Id IN(4,5,6) order by field(Id,4,5,6);
这将生成以下输出 −
+-----------+ | FirstName | +-----------+ | Sam | | Carol | | David | +-----------+ 3 rows in set (0.00 sec)
广告