MySQL-选择COUNT并返回NULL行 [英] MySQL - Select with COUNT returning a NULL row

查看:238
本文介绍了MySQL-选择COUNT并返回NULL行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效

SELECT DISTINCT  b.b_id 
FROM             b INNER JOIN c 
ON               b.b_id=c.b_id  
WHERE            c.active='yes' AND b.featured='no'

当结果应返回0行时,将返回count = 0的空行

SELECT DISTINCT  b.b_id, COUNT(c.c_id) AS count
FROM             b INNER JOIN c 
ON               b.b_id=c.b_id  
WHERE            c.active='yes' AND b.featured='no'

我做错什么了吗?

推荐答案

我认为您想要left join而不是inner join,因为当没有匹配项时,您想返回计数0而不是缺少的行给定b记录的c记录.

I think you want a left join instead of an inner join since you want to return a count of 0 instead of a missing row when there is no matching c record for a given b record.

此外,在使用聚合函数(例如count)时,还应包含group by.

Also, you should include a group by when using an aggregate function, such as count.

SELECT
    b.b_id,
    COUNT(DISTINCT c.c_id) AS count
FROM 
    b 
    LEFT JOIN c 
        ON b.b_id=c.b_id  
        AND c.active='yes' 
WHERE b.featured='no'
GROUP BY b.b_id

这篇关于MySQL-选择COUNT并返回NULL行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆