0

这有效

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'

难道我做错了什么?

4

3 回答 3

3

我认为您想要 aleft join而不是 an ,因为当给定记录inner join没有匹配记录时,您希望返回计数 0 而不是丢失的行。cb

此外,您应该group by在使用聚合函数时包含 a,例如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
于 2012-05-24T18:48:25.080 回答
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,恕我直言,这更具可读性。

于 2012-05-24T18:49:23.630 回答
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
于 2012-05-24T18:58:54.383 回答