此作品
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'
我做错了吗?
答案 0 :(得分:2)
我认为您需要left join
而不是inner join
,因为当给定{没有匹配的c
记录时,您希望返回0而不是丢失的行数{1}}记录。
此外,在使用聚合函数时,您应该包含b
,例如group by
。
count
答案 1 :(得分:1)
尝试将DISTINCT
放入 COUNT()
:
SELECT b.b_id, COUNT(DISTINCT c.c_id) AS count
FROM b
JOIN c ON b.b_id=c.b_id
WHERE c.active='yes'
AND b.featured='no'
GROUP BY 1
顺便说一句,请考虑像这样格式化你的SQL,这是更可读的恕我直言。
答案 2 :(得分:0)
我想尝试GROUP BY而不是DISTINCT。
SELECT 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'
GROUP BY b.b_id