在 MySQL IN() 中放置参数后,按降序对列进行排序?
为此,请将 FIELD() 函数与 DESC 一起使用。让我们首先创建一个表格 -
mysql> create table DemoTable -> ( -> Number int -> ); Query OK, 0 rows affected (0.57 sec)
使用插入命令将一些记录插入表中 -
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(50); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
输出
这将产生以下输出 -
+--------+ | Number | +--------+ | 10 | | 20 | | 30 | | 40 | | 50 | +--------+ 5 rows in set (0.00 sec)
以下是在 MySQL IN() 中放置参数后,按降序对列进行排序的查询 -
mysql> select *from DemoTable where Number IN (40,50,20,30,10) ORDER BY FIELD(Number, 40,50,20,30,10) DESC;
输出
这将产生以下输出 -
+--------+ | Number | +--------+ | 10 | | 30 | | 20 | | 50 | | 40 | +--------+ 5 rows in set (0.03 sec)
广告