2012-05-24 151 views
0

這工作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行返回,將返回一個空一行數= 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' 

難道我做錯了什麼?

+2

當您使用聚合函數('COUNT')時,您需要將'GROUP BY'作爲非聚合列。 MySQL甚至不應該允許該查詢,但它會導致不可預知的行爲... – bernie

+0

ahh,好吧,所以我已經在查詢結束時通過b.b_id刪除了DISTINCT和附加GROUP。是對的嗎? – lewicki

回答

2

我想你想的left join代替inner join因爲要返回缺失的行的計數0,而不是當有一個給定b記錄不匹配c記錄。

此外,使用聚合函數時應包含group by,例如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 
+1

這是正確的。 – lewicki

0

嘗試把DISTINCTCOUNT()

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這樣的,這是更具可讀性恕我直言。

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