Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Triển khai ORDER BY MySQL: x = cot3 nếu cot3 != NULL, ngược lại x = cot2

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ự:

  1. IFNULL(NULL, NULL) → NULL → lên đầu (NULL sort first mặc định)
  2. IFNULL(NULL, 'AUS') → 'AUS'
  3. IFNULL('Chris', NULL) → 'Chris'
  4. IFNULL('David', 'AUS') → 'David'
  5. 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.