GROUP BY在不存在时包含0



我有一个lists的表,每个表都包含posts。我想要一个查询,告诉我每个list有多少个posts,包括一个带有0的条目,每个列表没有任何帖子。

posts:

id  |  list_id
--------------
1   |   1  
2   |   1
3   |   2
4   |   2

lists:

id
---
1
2
3

应该返回:

list_id | num_posts
-------------------
1       | 2
2       | 2
3       | 0

我已经使用下面的查询做到了这一点,但感觉有点愚蠢,有效地进行分组,然后执行另一个子查询来填补空白:

WITH "count_data" AS (
  SELECT "posts"."list_id" AS "list_id", COUNT(DISTINCT "posts"."id") AS "num_posts"
  FROM "posts"
  INNER JOIN "lists" ON "posts"."list_id" = "lists"."id"
  GROUP BY "posts"."list_id"
)
SELECT "lists"."id", COALESCE("count_data"."num_posts", 0)
FROM "lists"
LEFT JOIN "count_data" ON "count_data"."list_id" = "lists"."id"
ORDER BY "count_data"."num_posts" DESC

谢谢!

直接左连接将更有效,避免在过程中使用大合并连接进行seq扫描:

select lists.id as list_id, count(posts.list_id) as num_posts
from lists
left join posts on posts.list_id = lists.id
group by lists.id

如果我理解你的问题,这应该工作:

SELECT List_ID, ISNULL(b.list_ID,0)
FROM lists a
LEFT JOIN (SELECT list_ID, COUNT(*)
      FROM posts
      GROUP BY list_ID
     )b
ON a.ID = b.list_ID

最新更新