Sắp xếp theo cột ưu tiên: Dùng IFNULL() trong ORDER BY
Hàm IFNULL(cot3, cot2) trả về cot3 nếu không NULL, ngược lại trả về cot2.
Tạo bảng và dữ liệu
mysql> create table DemoTable (
Name varchar(20),
CountryName varchar(20)
);
Query OK, 0 rows affected (0.61 sec)
mysql> insert into DemoTable values('Chris',NULL);
mysql> insert into DemoTable values('David','AUS');
mysql> insert into DemoTable values(NULL,'UK');
mysql> insert into DemoTable values(NULL,'AUS');
mysql> insert into DemoTable values(NULL,NULL);
Dữ liệu gốc
+-------+-------------+ | Name | CountryName | +-------+-------------+ | Chris | NULL | | David | AUS | | NULL | UK | | NULL | AUS | | NULL | NULL | +-------+-------------+
Truy vấn: Sắp xếp theo Name, nếu NULL thì dùng CountryName
mysql> select * from DemoTable order by ifnull(Name,CountryName);
Kết quả
+-------+-------------+ | Name | CountryName | +-------+-------------+ | NULL | NULL | | NULL | AUS | | Chris | NULL | | David | AUS | | NULL | UK | +-------+-------------+
Giải thích thứ tự:
IFNULL(NULL, NULL)→ NULL → lên đầu (NULL sort first mặc định)IFNULL(NULL, 'AUS')→ 'AUS'IFNULL('Chris', NULL)→ 'Chris'IFNULL('David', 'AUS')→ 'David'IFNULL(NULL, 'UK')→ 'UK'
Sắp xếp chữ: NULL, 'AUS', 'Chris', 'David', 'UK'.
Hàm tương tự: COALESCE(cot3, cot2, cot1, ...) - trả về giá trị đầu tiên không NULL trong danh sách.