2013-10-14 66 views
-1

我有一個請求,該計數所有未去除的紙幣和未去除的音符與特定值:MySQL的:條件帶走筆記

SELECT 
    catalogs.id AS id, 
    COUNT(DISTINCT t.id) AS total, 
    COUNT(DISTINCT c.id) AS closed 
FROM catalogs 
LEFT JOIN links t ON catalogs.id = t.catalog 
LEFT JOIN links c ON catalogs.id = c.catalog 
WHERE catalogs.removed = 0 
    AND (t.removed = 0 OR t.removed is NULL) 
    AND (c.removed = 0 OR c.removed is NULL) 
    AND (c.is_open = 0 OR c.is_open is NULL) 
GROUP BY catalogs.id 
ORDER BY catalogs.id; 

但在性反應的我只能看到註釋,其中總= 0或其中存在至少一個注意到c.is_open = 0

UPD 0:我不是非常接近與SQL,但我意識到我的方式試圖解決的問題......不要臉我:(

upd 1:我有另外一個(先回答)方式,使此查詢與SUM(),語法是

SUM(case when links.removed = 1 then 1 else 0 end) AS removed 

對我來說這是一個比較容易。

+2

請提供樣品的數據與實際的和預期的結果 –

回答

1

嘗試從WHERE子句中移動對其他列的檢查,以ON條款: -

SELECT 
    catalogs.id AS id, 
    COUNT(DISTINCT t.id) AS total, 
    COUNT(DISTINCT c.id) AS closed 
FROM catalogs 
LEFT JOIN links t ON catalogs.id = t.catalog AND t.removed = 0 
LEFT JOIN links c ON catalogs.id = c.catalog AND c.removed = 0 AND (c.is_open = 0 OR c.is_open is NULL) 
WHERE catalogs.removed = 0 
GROUP BY catalogs.id 
ORDER BY catalogs.id;