对多表联合查询中count函数的返回值为null的处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24309787/article/details/82768013

使用的数据库是createDB

select a.value as value1,if(b.value is null,0,b.value) as value2 from 
(select id,count(distinct channel_id) as value
 from temptable 
where id= '3' and type = '0'
group by id) a 
left join 
(select id, 
 count(distinct channel_id) as value
 from temptable 
where id= '3' and type = '1' 
group by id) b 
on a.id = b.id;

在关联表b中可能没有符合查询条件的数据 ,这样a关联b之后 b.value2就是一个null

程序就可能会报异常

所以我们可以使用if(b.value is null,0,b.value) as value2  来避免查询结果为null的情况,

使得结果为null时返回值为0。

以上仅供参考。

猜你喜欢

转载自blog.csdn.net/qq_24309787/article/details/82768013