我们可以在 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)
广告