为此,您可以将其IN()
与ORDER BY一起使用FIELD()
。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(FirstName) values('Chris'); mysql> insert into DemoTable(FirstName) values('Robert'); mysql> insert into DemoTable(FirstName) values('Mike'); mysql> insert into DemoTable(FirstName) values('Sam'); mysql> insert into DemoTable(FirstName) values('Carol'); mysql> insert into DemoTable(FirstName) values('David');
使用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)