GROUP BY包括0,其中不存在

Rob*_*ton 3 sql postgresql

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

例如.

posts:

id  |  list_id
--------------
1   |   1  
2   |   1
3   |   2
4   |   2
Run Code Online (Sandbox Code Playgroud)

lists:

id
---
1
2
3
Run Code Online (Sandbox Code Playgroud)

应该返回:

list_id | num_posts
-------------------
1       | 2
2       | 2
3       | 0
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

谢谢!

Den*_*rdy 5

直接离开连接会更有效,避免在进程中使用大型合并连接进行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
Run Code Online (Sandbox Code Playgroud)