要在MySQL中执行自定义排序,请使用ORDER BY FIELD()
。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int -> );
使用insert命令在表中插入一些记录:
mysql> insert into DemoTable values(101); mysql> insert into DemoTable values(103); mysql> insert into DemoTable values(102); mysql> insert into DemoTable values(105);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------+ | Id | +------+ | 101 | | 103 | | 102 | | 105 | +------+ 4 rows in set (0.00 sec)
这是执行自定义排序的查询-
mysql> select *from DemoTable order by field(Id,102,105,101,103);
这将产生以下输出-
+------+ | Id | +------+ | 102 | | 105 | | 101 | | 103 | +------+ 4 rows in set (0.00 sec)