仅为 MySQL 表中的 NULL 值设置值

mysqlmysqli database更新于 2025/11/2 20:28:17

使用 IFNULL 检查 NULL 值并使用 SET 命令设置值。让我们首先创建一个表 −

mysql> create table DemoTable817(Value int);
Query OK, 0 rows affected (0.53 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable817 values(10);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable817 values(null);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable817 values(20);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable817 values(null);
Query OK, 1 row affected (0.11 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable817;

这将产生以下输出 −

+-------+
| Value |
+-------+
| 10    |
| NULL  |
| 20    |
| NULL  |
+-------+
4 rows in set (0.00 sec)

以下是仅为 NULL 值设置值的查询 −

mysql> update DemoTable817 set Value=IFNULL(Value,0);
Query OK, 2 rows affected (0.17 sec)
Rows matched: 4 Changed: 2 Warnings: 0

让我们再次检查表记录 −

mysql> select *from DemoTable817;

这将产生以下输出 −

+-------+
| Value |
+-------+
| 10    |
| 0     |
| 20    |
| 0     |
+-------+
4 rows in set (0.00 sec)

相关文章


有用资源