のテーブルがありlists
、それぞれに が含まれていますposts
。投稿がないリストごとに 0 のエントリを含む、それぞれのリストの数を示すposts
クエリが必要です。list
例えば。
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
ありがとう!