在 MySQL 中使用两列进行自定义排序?
为此,请使用 ORDER BY 子句以及 CASE 语句。让我们首先创建一个表 -
mysql> create table DemoTable1610 -> ( -> Marks int, -> Name varchar(20) -> ) ; Query OK, 0 rows affected (0.51 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable1610 values(85,'John'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1610 values(78,'Carol'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1610 values(78,'John'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1610 values(85,'Carol'); Query OK, 1 row affected (0.20 sec)
使用选择语句子从表中显示所有记录 -
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)
广告