mysql查询一个字段的不同值的数量

SELECT 
        sum(if(handle_type = '0',1,0)) as dfp,
        sum(if(handle_type = '1',1,0)) as dcz,
        sum(if(handle_type = '2',1,0)) as ddc,
        sum(if(handle_type = '3',1,0)) as ydcdxh,
        sum(if(handle_type = '4',1,0)) as yxh

上面sql语句没有判断null值,如果全为0的时候则会出现对象为null值,所以需要下面这种写法

IFNULL(sum(if(handle_type = '0',1,0)),0) as dfp,
IFNULL(sum(if(handle_type = '1',1,0)),0) as dcz,
IFNULL(sum(if(handle_type = '2',1,0)),0) as ddc,
IFNULL(sum(if(handle_type = '3',1,0)),0) as ydcdxh,
IFNULL(sum(if(handle_type = '4',1,0)),0) as yxh


版权声明:本文为weixin_40935738原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。