我們可以在 MySQL ORDER BY 中使用 IFNULL 嗎?


可以在 ORDER BY 子句中使用 IFNULL。語法如下:

SELECT *FROM yourTableName ORDER BY IFNULL(yourColumnName1,yourColumnName2);

為了理解上面的語法,我們建立一個表格。建立表格的查詢如下:

mysql> create table IfNullDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(10),
   -> ProductWholePrice float,
   -> ProductRetailPrice float,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.19 sec)

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

mysql> insert into IfNullDemo(ProductName,ProductWholePrice,ProductRetailPrice) values('Product-1',99.50,150.50);
Query OK, 1 row affected (0.21 sec)
mysql> insert into IfNullDemo(ProductName,ProductWholePrice,ProductRetailPrice) values('Product-2',NULL,76.56);
Query OK, 1 row affected (0.18 sec)
mysql> insert into IfNullDemo(ProductName,ProductWholePrice,ProductRetailPrice) values('Product-3',105.40,NULL);
Query OK, 1 row affected (0.20 sec)
mysql> insert into IfNullDemo(ProductName,ProductWholePrice,ProductRetailPrice) values('Product-4',NULL,NULL);
Query OK, 1 row affected (0.18 sec)
mysql> insert into IfNullDemo(ProductName,ProductWholePrice,ProductRetailPrice) values('Product-5',209.90,400.50);
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from IfNullDemo;

輸出如下:

+----+-------------+-------------------+--------------------+
| Id | ProductName | ProductWholePrice | ProductRetailPrice |
+----+-------------+-------------------+--------------------+
|  1 | Product-1   |              99.5 |              150.5 |
|  2 | Product-2   |              NULL |              76.56 |
|  3 | Product-3   |             105.4 |               NULL |
|  4 | Product-4   |              NULL |               NULL |
|  5 | Product-5   |             209.9 |              400.5 |
+----+-------------+-------------------+--------------------+
5 rows in set (0.02 sec)

以下是 null 排序查詢:

mysql> select *from IfNullDemo order by ifnull(ProductWholePrice,ProductRetailPrice);

輸出如下:

+----+-------------+-------------------+--------------------+
| Id | ProductName | ProductWholePrice | ProductRetailPrice |
+----+-------------+-------------------+--------------------+
|  4 | Product-4  |               NULL |               NULL |
|  2 | Product-2  |               NULL |              76.56 |
|  1 | Product-1  |               99.5 |              150.5 |
|  3 | Product-3  |              105.4 |               NULL |
|  5 | Product-5  |              209.9 |              400.5 |
+----+-------------+-------------------+--------------------+
5 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

284 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告