Postgresql 查找包含特定id Postgre的所有数组

Postgresql 查找包含特定id Postgre的所有数组,postgresql,common-table-expression,Postgresql,Common Table Expression,我将邻接树存储在表中。我编写了一个递归公共表表达式来查找树中每个节点的所有上升点。 所以当我写SELECT*fromtree时 我明白了: id | ancestors ----+--------------- 0 | {} <- ROOT 1 | {0} 2 | {0} 4 | {0} 19 | {0} 45 | {0} 3 | {0,1} 5 | {0,4} 6 | {0,4} 8 | {0,4} 11 | {0,1} 22 | {0

我将邻接树存储在表中。我编写了一个递归公共表表达式来查找树中每个节点的所有上升点。 所以当我写SELECT*fromtree时

我明白了:

 id |   ancestors   
----+---------------
  0 | {} <- ROOT
  1 | {0}
  2 | {0}
  4 | {0}
 19 | {0}
 45 | {0}
  3 | {0,1}
  5 | {0,4}
  6 | {0,4}
  8 | {0,4}
 11 | {0,1}
 22 | {0,2}
  7 | {0,4,5}
  9 | {0,4,6}
对于这个查询,如果id=0的节点是根,它应该给我树中所有节点的数量减去1

我试着写这样的东西:

SELECT count(*) from tree
WHERE id = any(tree.ancestors)
group by id;

但它实际上返回0行

要在整个树中搜索每个id,它是一个带条件的自连接:

with tree(id, ancestors) as (
values
    (0, '{}'::int[]),
    (1, '{0}'),
    (2, '{0}'),
    (4, '{0}'),
    (19, '{0}'),
    (45, '{0}'),
    (3, '{0,1}'),
    (5, '{0,4}'),
    (6, '{0,4}'),
    (8, '{0,4}'),
    (11, '{0,1}'),
    (22, '{0,2}'),
    (7, '{0,4,5}'),
    (9, '{0,4,6}')
)

select t1.id, count(t2.*)
from tree t1
join tree t2 on t1.id = any(t2.ancestors)
group by 1
order by 1

 id | count 
----+-------
  0 |    13
  1 |     2
  2 |     1
  4 |     5
  5 |     1
  6 |     1
(6 rows)
请注意,如果要获取所有ID,而这些ID没有出现在祖先中,则应使用左连接

with tree(id, ancestors) as (
values
    (0, '{}'::int[]),
    (1, '{0}'),
    (2, '{0}'),
    (4, '{0}'),
    (19, '{0}'),
    (45, '{0}'),
    (3, '{0,1}'),
    (5, '{0,4}'),
    (6, '{0,4}'),
    (8, '{0,4}'),
    (11, '{0,1}'),
    (22, '{0,2}'),
    (7, '{0,4,5}'),
    (9, '{0,4,6}')
)

select t1.id, count(t2.*)
from tree t1
join tree t2 on t1.id = any(t2.ancestors)
group by 1
order by 1

 id | count 
----+-------
  0 |    13
  1 |     2
  2 |     1
  4 |     5
  5 |     1
  6 |     1
(6 rows)