MySQL ORDER BY ASC 並顯示 NULL 值到底部?


為此,將 CASE 語句與 ORDER BY 結合使用。讓我們首先建立一個表 -

mysql> create table DemoTable1937
   (
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable1937 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('Adam');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('John');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1937 values('Bob');
Query OK, 1 row affected (0.00 sec)

使用 select 命令在表中顯示所有記錄 -

mysql> select * from DemoTable1937;

這將產生以下輸出 -

+-------+
| Name  |
+-------+
| Chris |
| NULL  |
| Adam  |
| John  |
|       |
| NULL  |
| Bob   |
+-------+
7 rows in set (0.00 sec)

以下是 ORDER BY ASC 並顯示 NULL 值到底部的查詢

mysql> select * from DemoTable1937
   order by case when Name IS NULL then 100
   when Name='' then 101
   else 103
   end desc
   ,
   Name asc;

這將產生以下輸出 -

+-------+
| Name  |
+-------+
| Adam  |
| Bob   |
| Chris |
| John  |
|       |
| NULL  |
| NULL  |
+-------+
7 rows in set (0.00 sec)

更新於: 2019-12-30

449 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.