MySQL ORDER BY 带 CASE WHEN
为此,你可以使用 ORDER BY CASE 语句。我们先创建一个表 -
mysql> create table DemoTable order by with vas Color varchar(100) ); Query OK, 0 rows affected (0.64 sec)
用插入命令在表中插入某些记录 -
mysql> insert into DemoTable values('Red'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Green'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Blue'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Yellow'); Query OK, 1 row affected (0.18 sec)
用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+--------+ | Color | +--------+ | Red | | Green | | Blue | | Yellow | +--------+ 4 rows in set (0.00 sec)
以下是用 CASE WHEN 排序的查询 -
mysql> select *from DemoTable order by case Color when 'Blue' then 10 when 'Green' then 20 when 'Yellow' then 30 else 100 end ;
这将生成以下输出 -
+--------+ | Color | +--------+ | Blue | | Green | | Yellow | | Red | +--------+ 4 rows in set (0.00 sec)
广告