mysql count(*)分组后ifnull无效
因为之前用oracle比较多,mysql没有经过系统性学习,所以这次碰到这个问题,弄了比较久,在此记录一下
需求
根据发票id和单位来统计,一个id下挂靠多少个单位
最开始的错误语句
select count(t.costcenter) as countnum from trip_plane_settlement t where t.itineraryid = #{itineraryid} group by t.itineraryid, t.costcenter
后台用int来接收时,如果返回空就会抛出异常,然后我就想用ifnull()函数来实现,如果为空时返回0,但是发现还是返回还是为空,后来查阅资料之后,才发现如果分组之后,如果查询条件查不到数据时还是会返回null,后面尝试过 case when 来实现,发下还是会返回null,因为查不到数据时,整个结果集都是空的,函数就不会生效。
后面就想用嵌套循环来实现试试,发现果然可以。
解决代码
select ifnull(count(*), 0) as countnum from ( select count(t.costcenter) as countnum, t.itineraryid, t.costcenter from trip_plane_settlement t group by t.itineraryid, t.costcenter ) t1 where t1.itineraryid = #{itineraryid}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论