更新时间: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