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

Sắp xếp kết quả MySQL: NOT NULL lên trước, NULL sau cùng

Sử dụng biểu thức logic (cot IS NULL) trong ORDER BY: FALSE (0) xếp trước TRUE (1) → NOT NULL lên trước.

Ví dụ minh họa

Tạo bảng:

mysql> CREATE TABLE DemoTable1357 (StudentName VARCHAR(40), StudentCountryName VARCHAR(30));

Chèn dữ liệu (có NULL):

mysql> INSERT INTO DemoTable1357 VALUES('Chris', 'US'), ('David', NULL), ('David', 'AUS'), ('Carol', NULL), ('Mike', 'UK');

Xem dữ liệu gốc:

mysql> SELECT * FROM DemoTable1357;
+-------------+--------------------+
| StudentName | StudentCountryName |
+-------------+--------------------+
| Chris       | US                 |
| David       | NULL               |
| David       | AUS                |
| Carol       | NULL               |
| Mike        | UK                 |
+-------------+--------------------+

Sắp xếp: NOT NULL trước, NULL sau, trong nhóm sắp theo tên:

mysql> SELECT * FROM DemoTable1357 ORDER BY (StudentCountryName IS NULL), StudentName;

Kết quả:

+-------------+--------------------+
| StudentName | StudentCountryName |
+-------------+--------------------+
| Chris       | US                 |
| David       | AUS                |
| Mike        | UK                 |
| Carol       | NULL               |
| David       | NULL               |
+-------------+--------------------+

Giải thích: StudentCountryName IS NULL trả về 0 (false) cho NOT NULL, 1 (true) cho NULL. ORDER BY 0, ... trước, ORDER BY 1, ... sau.

Thay thế: ORDER BY StudentCountryName IS NULL, StudentCountryName (sắp NULL theo tên cột).