將空值轉換為 NULL 的 MySQL 查詢?


使用 SET 和 WHERE 可以輕鬆地將空值轉換為 NULL。讓我們首先建立一個表 −

mysql> create table DemoTable1315
-> (
-> CountryName varchar(10)
-> );
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令在表中插入一些記錄。我們在這裡也設定了一些空值 −

mysql> insert into DemoTable1315 values('US');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1315 values('');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1315 values('UK');
Query OK, 1 row affected (0.70 sec)
mysql> insert into DemoTable1315 values('');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1315 values('');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1315 values('AUS');
Query OK, 1 row affected (0.14 sec)

使用 select 語句從表中顯示所有記錄 −

mysql> select *from DemoTable1315;

輸出

+-------------+
| CountryName |
+-------------+
| US          |
|             |
| UK          |
|             |
|             |
| AUS         |
+-------------+
6 rows in set (0.00 sec)

以下是將空值轉換為 NULL 的查詢 −

mysql> update DemoTable1315 set CountryName=NULL where CountryName='';
Query OK, 3 rows affected (0.16 sec)
Rows matched: 3 Changed: 3 Warnings: 0

讓我們再次檢查表記錄 −

mysql> select *from DemoTable1315;

輸出

+-------------+
| CountryName |
+-------------+
| US          |
| NULL        |
| UK          |
| NULL        |
| NULL        |
| AUS         |
+-------------+
6 rows in set (0.00 sec)

更新於: 04-Nov-2019

943 瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告