MySQL ORDER BY和CASE WHEN
为此,您可以使用ORDERBYCASE语句。让我们首先创建一个表-
mysql> create table DemoTable order by with vas Color varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Red'); mysql> insert into DemoTable values('Green'); mysql> insert into DemoTable values('Blue'); mysql> insert into DemoTable values('Yellow');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+ | Color | +--------+ | Red | | Green | | Blue | | Yellow | +--------+ 4 rows in set (0.00 sec)
这是用CASEWHEN订购的查询-
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)