如何在 MySQL "IN" 查询中保持顺序?

mysqlmysqli database

您可以借助 field 命令在 MySQL IN 查询中保持顺序。语法如下 −

select *from yourTableName anyVariableName where anyVariableName.yourColumnName in(value1,value2,......N)
order by field(anyVariableName.yourColumnName,value1,value2,......N);

为了实现上述语法,让我们创建一个表 −

mysql> create table OrderInDemo
   −> (
      −> Id int,
      −> Name varchar(100),
      −> Age int
   −> );
Query OK, 0 rows affected (1.24 sec)

现在让我们在表中插入一些记录。插入记录的查询如下 −

mysql> insert into OrderInDemo values(90,'David',23);
Query OK, 1 row affected (0.10 sec)

mysql> insert into OrderInDemo values(9,'Sam',24);
Query OK, 1 row affected (0.59 sec)

mysql> insert into OrderInDemo values(10,'Carol',19);
Query OK, 1 row affected (0.25 sec)

mysql> insert into OrderInDemo values(1,'John',26);
Query OK, 1 row affected (0.42 sec)

mysql> insert into OrderInDemo values(3,'Johnson',25);
Query OK, 1 row affected (0.18 sec)

mysql> insert into OrderInDemo values(2,'Ramit',20);
Query OK, 1 row affected (0.18 sec)

使用 select 语句显示所有记录,查询如下 −

mysql> select *from OrderInDemo;

以下是输出 −

+------+---------+------+
| Id   | Name    | Age  |
+------+---------+------+
|   90 | David   |   23 |
|    9 | Sam     |   24 |
|   10 | Carol   |   19 |
|    1 | John    |   26 |
|    3 | Johnson |   25 |
|    2 | Ramit   |   20 |
+------+---------+------+
6 rows in set (0.00 sec)

实现我们在开始时讨论的语法,以在 MySQL IN 查询中保持顺序。查询如下 −

mysql> select *from OrderInDemo OD where OD.Id in(10,1,3)
   −> order by field(OD.Id,10,1,3);

以下是按查询中提供的顺序显示结果的输出 −

+------+---------+------+
| Id   | Name    | Age  |
+------+---------+------+
|   10 | Carol   |   19 |
|    1 | John    |   26 |
|    3 | Johnson |   25 |
+------+---------+------+
3 rows in set (0.00 sec)

相关文章