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

Đếm giá trị NULL trong hai cột khác nhau và hiển thị trong một câu SELECT MySQL

Sử dụng IS NULL để kiểm tra giá trị NULL.

Tạo bảng demo

mysql> create table DemoTable (
    -> Number1 int,
    -> Number2 int
    -> );
Query OK, 0 rows affected (0.62 sec)

Chèn dữ liệu có giá trị NULL

mysql> insert into DemoTable values(1, NULL);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(NULL, NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(3, NULL);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(NULL, 90);
Query OK, 1 row affected (0.11 sec)

Hiển thị dữ liệu

mysql> select * from DemoTable;

Kết quả

+---------+---------+
| Number1 | Number2 |
+---------+---------+
| 1       | NULL    |
| NULL    | NULL    |
| 3       | NULL    |
| NULL    | 90      |
+---------+---------+
4 rows in set (0.00 sec)

Truy vấn đếm NULL cho từng cột trong một câu SELECT

mysql> select
    -> (select count(*) from DemoTable where Number1 is null) as FirstColumnNullValue,
    -> (select count(*) from DemoTable where Number2 is null) as SecondColumnNullValue
    -> ;

Kết quả

+----------------------+-----------------------+
| FirstColumnNullValue | SecondColumnNullValue |
+----------------------+-----------------------+
| 2                    | 3                     |
+----------------------+-----------------------+
1 row in set (0.00 sec)

Giải thích: Sử dụng subquery trong SELECT để đếm riêng cho từng cột.

Cách thay thế hiệu quả hơn (một lần quét bảng):

select 
    sum(case when Number1 is null then 1 else 0 end) as FirstColumnNullValue,
    sum(case when Number2 is null then 1 else 0 end) as SecondColumnNullValue
from DemoTable;

Cách này chỉ quét bảng một lần thay vì hai lần như subquery.