在 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)

更新於: 17-Dec-2019

160 次瀏覽

啟動 事業

完成課程獲得認證

開始
廣告