Computer >> Máy Tính >  >> Lập trình >> MySQL

Hiển thị kết quả không có giá trị null trước và sau đó là giá trị null trong MySQL

Đầu tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable1357
    -> (
    -> StudentName varchar(40),
    -> StudentCountryName varchar(30)
    -> );
Query OK, 0 rows affected (0.49 sec)

Chèn một số bản ghi vào bảng bằng lệnh chèn -

mysql> insert into DemoTable1357 values('Chris','US');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1357 values('David',NULL);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1357 values('David','AUS');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1357 values('Carol',NULL);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1357 values('Mike','UK');
Query OK, 1 row affected (0.15 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select * from DemoTable1357;

Điều này sẽ tạo ra kết quả sau -

+-------------+--------------------+
| StudentName | StudentCountryName |
+-------------+--------------------+
| Chris       | US                 |
| David       | NULL               |
| David       | AUS                |
| Carol       | NULL               |
| Mike        | UK                 |
+-------------+--------------------+
5 rows in set (0.00 sec)

Sau đây là truy vấn để hiển thị kết quả không có giá trị null trước và sau đó là giá trị null -

mysql> select * from DemoTable1357
    -> order by (StudentCountryName IS NULL),StudentName;

Điều này sẽ tạo ra kết quả sau -

+-------------+--------------------+
| StudentName | StudentCountryName |
+-------------+--------------------+
| Chris       | US                 |
| David       | AUS                |
| Mike        | UK                 |
| Carol       | NULL               |
| David       | NULL               |
+-------------+--------------------+
5 rows in set (0.00 sec)