表tree
是PostgreSQL 8.3+中带有祖先数组的示例表:
----+-----------
id | ancestors
----+-----------
1 | {}
2 | {1}
3 | {1,2}
4 | {1}
5 | {1,2}
6 | {1,2}
7 | {1,4}
8 | {1}
9 | {1,2,3}
10 | {1,2,5}
要获取后代的每个id计数,我可以这样做:
SELECT 1 AS id, COUNT(id) AS descendant_count FROM tree WHERE 1 = ANY(ancestors)
UNION
SELECT 2 AS id, COUNT(id) AS descendant_count FROM tree WHERE 2 = ANY(ancestors)
UNION
SELECT 3 AS id, COUNT(id) AS descendant_count FROM tree WHERE 3 = ANY(ancestors)
UNION
SELECT 4 AS id, COUNT(id) AS descendant_count FROM tree WHERE 4 = ANY(ancestors)
UNION
SELECT 5 AS id, COUNT(id) AS descendant_count FROM tree WHERE 5 = ANY(ancestors)
UNION
SELECT 6 AS id, COUNT(id) AS descendant_count FROM tree WHERE 6 = ANY(ancestors)
UNION
SELECT 7 AS id, COUNT(id) AS descendant_count FROM tree WHERE 7 = ANY(ancestors)
UNION
SELECT 8 AS id, COUNT(id) AS descendant_count FROM tree WHERE 8 = ANY(ancestors)
UNION
SELECT 9 AS id, COUNT(id) AS descendant_count FROM tree WHERE 9 = ANY(ancestors)
UNION
SELECT 10 AS id, COUNT(id) AS descendant_count FROM tree WHERE 10 = ANY(ancestors)
并得到以下结果:
----+------------------
id | descendant_count
----+------------------
1 | 9
2 | 5
3 | 1
4 | 1
5 | 1
6 | 0
7 | 0
8 | 0
9 | 0
10 | 0
我猜应该存在较短或更智能的查询语句才能获得相同的结果,这可能吗?也许像WITH RECURSIVE
或使用带有循环的函数来生成查询?
答案 0 :(得分:3)
看起来就像一个递归查询的案例,但这更简单:
只是嵌套,分组并计数:
SELECT id AS ancestor, COALESCE (a1.id, 0) AS descendants_count
FROM tree
LEFT JOIN (
SELECT a.id, count(*) AS descendant_count
FROM tree t, unnest(t.ancestors) AS a(id)
GROUP BY 1
) a1 USING (id)
ORDER BY 1;
并且,要包括根本没有任何后代的祖先,请加入LEFT JOIN
。
有一个隐式LATERAL
联接到集合返回函数unnest()
。参见:
在旁边:
如果您最终不得不使用多个UNION
子句,请考虑使用UNION ALL
。参见:
答案 1 :(得分:1)
您的工会实际上只是自我联接...
SELECT
tree.id,
COUNT(descendant.id) AS descendant_count
FROM
tree
LEFT JOIN
tree AS descendant
ON tree.id = ANY(descendant.ancestors)
GROUP BY
tree.id