将空值转换为 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 浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.