如何在 MySQL 中按字段值执行自定义排序?
若要按字段值在 MySQL 中执行自定义排序,请在 ORDER BY 中使用 FIELD() 方法。让我们首先创建一个表
mysql> create table DemoTable (StudentId int); Query OK, 0 rows affected (0.58 sec)
以下查询使用 insert 命令在表中插入一些记录
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(110); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(70); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(120); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(140); Query OK, 1 row affected (0.14 sec)
以下查询使用 select 命令从表中显示记录
mysql> select *from DemoTable;
这将产生以下输出
+-----------+ | StudentId | +-----------+ | 100 | | 110 | | 90 | | 70 | | 120 | | 140 | +-----------+ 6 rows in set (0.00 sec)
以下查询用于执行 MySQL 按字段值进行自定义排序
mysql> select *from DemoTable order by field(StudentId,'100','70','140','90','120','110');
这将产生以下输出
+-----------+ | StudentId | +-----------+ | 100 | | 70 | | 140 | | 90 | | 120 | | 110 | +-----------+ 6 rows in set (0.00 sec)
广告