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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP