首页 > 开发 > MySQL > 正文

为什么sum(0)有时为null有时为0

2017-09-08 08:51:05  来源:网友分享

1.有以下mysql查询语句

select sum(CASE state when 3 then 1 else 0 end) as deliver,count(1) as orderAll from table

2.理论上这句话的意思是,查询table表中所有状态为3的订单即为发货数量,以及查询总订单数。可是当table为空白时,查询到的内容为

deliverorderAll
(Null)0

3.自我剖析

sum(CASE state when 3 then 1 else 0 end)

这段代码的逻辑应该为当state字段为3时记为1,其他时记为0,空表则state无值,此时逻辑是

select sum(0) as deliver,count(1) as orderAll from table

4.进一步深挖发现,当table为空表时,sum(0)为null;当table非空时,sum(0)为0.

#1.table为空表select sum(0) from table
SUM(0)
(Null)
#2.table不为空表select sum(0) from table
SUM(0)
0

5.问:为什么两个sum(0)的结果不一样?

解决方案

https://dev.mysql.com/doc/ref...

https://dev.mysql.com/doc/ref...

另外,就算你的表不是空,但如果所有state字段均为NULL,那sum出来的结果也是NULL,如果不想为NULL,那就多套一个IFNULL函数。

不过,最佳实践应该是不允许数据表有NULL值存在。