我有一个请求,它计算所有未删除的笔记和具有特定值的未删除笔记:
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
对我来说,这个更容易。