且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL-选择COUNT并返回NULL行

更新时间:2023-01-31 14:10:37

我认为您想要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