如何透過某個欄位按降序排序,但首先列出 NULL 值?


若要按某個欄位排序,但首先列出 NULL 值,你需要使用以下語法。這將按降序排序 −

select yourColumnName from yourTableName group by yourColumnName is null desc,yourColumnName desc;

為了理解上述語法,我們首先建立一個表 −

mysql> create table OrderByNullFirstDemo
   −> (
   −> StudentId int
   −> );
Query OK, 0 rows affected (0.56 sec)

使用 insert 命令在表中插入一些記錄。查詢如下 −

mysql> insert into OrderByNullFirstDemo values(100);
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByNullFirstDemo values(200);
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByNullFirstDemo values(150);
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByNullFirstDemo values(NULL);
Query OK, 1 row affected (0.15 sec)

使用 select 語句顯示錶中的所有記錄。查詢以顯示所有記錄如下 −

mysql> select *from OrderByNullFirstDemo;

以下是輸出 −

+-----------+
| StudentId |
+-----------+
|       100 |
|       200 |
|       150 |
|      NULL |
+-----------+
4 rows in set (0.00 sec)

執行我們在開頭討論的語法,以按降序執行排序並顯示空值 −

mysql> select StudentId from OrderByNullFirstDemo group by StudentId is null desc,StudentId desc;

以下是輸出 −

+-----------+
| StudentId |
+-----------+
|      NULL |
|       200 |
|       150 |
|       100 |
+-----------+
4 rows in set, 2 warnings (0.00 sec)

更新於: 30-7 月-2019

67 次瀏覽

開啟你的 職業

完成課程獲得認證

立即開始
廣告
© . All rights reserved.