-1

我有一个请求,它计算所有未删除的笔记和具有特定值的未删除笔记:

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

对我来说,这个更容易。

4

1 回答 1

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;
于 2013-10-14T09:31:07.133 回答