计算祖先数组后代数量的最佳方法?

Best way to count number of descendants from ancestors array?

Table tree 是 PostgreSQL 8.3+ 中带有祖先数组的示例 table:

----+-----------
 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 或使用循环创建函数来生成查询?

乍一看像递归查询的情况,但这个更简单:
只是 unnest,分组和计数:

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。参见:

你的联合集实际上只是一个自连接...

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