MySQL:条件带走笔记

MySQL:条件带走笔记,mysql,where,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

我有一个请求,它统计所有未移动的笔记和具有特定值的未移动笔记:

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;
但在response中,我只能看到notes,其中total=0,或者至少存在一个c.is_open=0的notes

upd 0:我对sql不是很熟悉,但我意识到我试图解决问题的方法。。。我真丢脸:(

upd 1:我找到了另一种(答案中的第一个)使用SUM()进行查询的方法,语法是

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

对我来说,这一项更容易。

尝试将其他列上的检查从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;

请提供实际和预期结果的样本数据