如果查询返回 MySQL 中的空值,如何将值设为 0?
为此,可以使用 IFNULL()。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Value int -> ); Query OK, 0 rows affected (0.71 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(Value) values(100); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(Value) values(140); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Value) values(200); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable(Value) values(450); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Value) values(null); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Value) values(90); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Value) values(null); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+----+-------+ | Id | Value | +----+-------+ | 1 | 100 | | 2 | 140 | | 3 | 200 | | 4 | 450 | | 5 | NULL | | 6 | 90 | | 7 | NULL | +----+-------+ 7 rows in set (0.00 sec)
以下是在 MySQL 中如果查询返回空值,则将值设为 0 的查询。
mysql> select ifnull(Value,0) AS Value from DemoTable;
输出
+-------+ | Value | +-------+ | 100 | | 140 | | 200 | | 450 | | 0 | | 90 | | 0 | +-------+ 7 rows in set (0.00 sec)