按 MySQL 'IN' 子句中的位置 (ORDER BY) 获取返回的记录集

mysqlmysqli database

要返回记录集顺序,您需要使用 FIND_IN_SET()。让我们首先创建一个表 −

mysql> create table recordSetOrderDemo
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(30)
   -> );
Query OK, 0 rows affected (0.63 sec)

下面是使用 insert 命令在表中插入一些记录的查询 −

mysql> insert into recordSetOrderDemo values(20,"John");
Query OK, 1 row affected (0.20 sec)

mysql> insert into recordSetOrderDemo values(10,"Larry");
Query OK, 1 row affected (0.14 sec)

mysql> insert into recordSetOrderDemo values(100,"Mike");
Query OK, 1 row affected (0.14 sec)

mysql> insert into recordSetOrderDemo values(50,"Sam");
Query OK, 1 row affected (0.11 sec)

mysql> insert into recordSetOrderDemo values(10,"David");
Query OK, 1 row affected (0.18 sec)

以下是使用 select 语句显示表中的所有记录的查询 −

mysql> select *from recordSetOrderDemo;

这将产生以下输出 −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
| 20         | John         |
| 10         | Larry        |
| 100        | Mike         |
| 50         | Sam          |
| 10         | David        |
+------------+--------------+
5 rows in set (0.00 sec)

以下是返回记录集顺序的查询 −

mysql> select *from recordSetOrderDemo where EmployeeId IN(100,10,20,50)
-> ORDER BY FIND_IN_SET(EmployeeId,'100,10,20,50');

这将产生以下输出 −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
| 100        | Mike         |
| 10         | Larry        |
| 10         | David        |
| 20         | John         |
| 50         | Sam          |
+------------+--------------+
5 rows in set (0.03 sec)

相关文章