是否能按照 MySQL `IN(…)` 语句中的值返回查询结果?


当然可以,使用 MySQL 的 ORDER BY FIELD() 就可以实现。首先创建一个表 -

mysql> create table DemoTable
   -> (
   -> Number int
   -> );
Query OK, 0 rows affected (0.54 sec)

使用 insert 命令向表中插入一些记录 -

mysql> insert into DemoTable values(19);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(34);
Query OK, 1 row affected (0.32 sec)

mysql> insert into DemoTable values(28);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values(25);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values(29);
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values(24);
Query OK, 1 row affected (0.14 sec)

使用 select 语句从表中显示所有记录 -

mysql> select *from DemoTable;

将产生以下输出 -

+--------+
| Number |
+--------+
|     19 |
|     30 |
|     34 |
|     28 |
|     25 |
|     29 |
|     24 |
+--------+
7 rows in set (0.00 sec)

以下是按照值的顺序返回结果的查询 -

mysql> select *from DemoTable
   -> ORDER BY FIELD(Number, 30,19,34,25,28,29,24) ;

将产生以下输出,显示的顺序与值相同 -

+--------+
| Number |
+--------+
|     30 |
|     19 |
|     34 |
|     25 |
|     28 |
|     29 |
|     24 |
+--------+
7 rows in set (0.00 sec)

更新日期: 30-Jul-2019

172 次浏览

开启您的职业生涯

通过完成课程取得认证

开始
广告