使用 CASE 语句按字段对 MySQL 进行排序
可使用 CASE 语句根据字段排序。我们首先创建一个表 −
mysql> create table DemoTable(StudentId varchar(100)); Query OK, 0 rows affected (1.69 sec)
使用插入命令在表内插入一些记录 −
mysql> insert into DemoTable values('STU-980'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values('STU-1029'); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values('STU-189'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('STU-890'); Query OK, 1 row affected (0.38 sec)
使用 select 语句显示该表内所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+-----------+ | StudentId | +-----------+ | STU-980 | | STU-1029 | | STU-189 | | STU-890 | +-----------+ 4 rows in set (0.00 sec)
以下是 MySQL 按字段排序的查询 −
mysql> select *from DemoTable order by case WHEN StudentId = 'STU-890' THEN 1 WHEN StudentId = 'STU-1029' THEN 2 WHEN StudentId = 'STU-980' THEN 3 WHEN StudentId = 'STU-189' THEN 4 end;
这将产生以下输出 −
+-----------+ | StudentId | +-----------+ | STU-890 | | STU-1029 | | STU-980 | | STU-189 | +-----------+ 4 rows in set (0.08 sec)
广告