要在MySQL中执行自定义的按字段排序值,请使用FIELD()
ORDER BY中的方法。让我们首先创建一个表:
mysql> create table DemoTable (StudentId int);
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable values(100); mysql> insert into DemoTable values(110); mysql> insert into DemoTable values(90); mysql> insert into DemoTable values(70); mysql> insert into DemoTable values(120); mysql> insert into DemoTable values(140);
以下是使用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)