为此,将ORDER BY子句与CASE语句一起使用。让我们首先创建一个表-
mysql> create table DemoTable1610 -> ( -> Marks int, -> Name varchar(20) -> ) ;
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1610 values(85,'John'); mysql> insert into DemoTable1610 values(78,'Carol'); mysql> insert into DemoTable1610 values(78,'John'); mysql> insert into DemoTable1610 values(85,'Carol');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1610;
这将产生以下输出
+-------+-------+ | Marks | Name | +-------+-------+ | 85 | John | | 78 | Carol | | 78 | John | | 85 | Carol | +-------+-------+ 4 rows in set (0.00 sec)
这是使用MySQL中两个不同的列进行自定义排序的查询-
mysql> select * from DemoTable1610 -> order by Marks,case when Name='Carol' then 1 else 0 end;
这将产生以下输出
+-------+-------+ | Marks | Name | +-------+-------+ | 78 | John | | 78 | Carol | | 85 | John | | 85 | Carol | +-------+-------+ 4 rows in set (0.00 sec)