我有一张lists
表,每个表都包含posts
。我想要一个查询,告诉我每个posts
有多少list
个,包括每个没有任何帖子的列表为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
谢谢!
答案 0 :(得分: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
答案 1 :(得分:0)
如果我理解你的问题,这应该有效:
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