如何計算 MySQL 中的空值?


要計算 MySQL 中的空值,可以使用 CASE 語句。讓我們先看一個示例並建立一個表 -

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.77 sec)

使用 insert 命令向表中插入一些記錄 -

mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values(null);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(FirstName) values('');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values(null);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values(null);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(FirstName) values('Bob');
Query OK, 1 row affected (0.15 sec)

以下是使用 select 語句從表中顯示所有記錄的查詢 -

mysql> select *from DemoTable;

這將產生以下輸出 -

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1  | John      |
| 2  | NULL      |
| 3  |           |
| 4  | Larry     |
| 5  |           |
| 6  | NULL      |
| 7  | NULL      |
| 8  | Bob       |
+----+-----------+
8 rows in set (0.00 sec)

以下是計算 MySQL 中空值數的查詢 -

mysql> select sum(case when FirstName IS NULL then 1 else 0 end) as NUMBER_OF_NULL_VALUE from DemoTable;

這將產生以下輸出 -

+----------------------+
| NUMBER_OF_NULL_VALUE |
+----------------------+
| 3                    |
+----------------------+
1 row in set (0.00 sec)

更新於: 30-Jul-2019

920 次瀏覽

開啟你的職業

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.