MySQL:条件带走笔记

时间:2013-10-14 08:28:58

标签: mysql where

我有一个请求,会将所有未删除的笔记和未删除的笔记计入特定值:

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;

但是在回答中我只能看到音符,其中total = 0或者至少存在一个音符,其中c.is_open = 0。

upd 0:我与sql并不是很接近,但我意识到我试图解决这个问题的方式......对我感到羞耻:(

upd 1:我得到另一个(第一个回答)方式用SUM()进行此查询,语法是

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

对我来说这个更容易。

1 个答案:

答案 0 :(得分: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;