为此,您可以使用IFNULL()
。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Value int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Value) values(100); mysql> insert into DemoTable(Value) values(140); mysql> insert into DemoTable(Value) values(200); mysql> insert into DemoTable(Value) values(450); mysql> insert into DemoTable(Value) values(null); mysql> insert into DemoTable(Value) values(90); mysql> insert into DemoTable(Value) values(null);
使用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)