Postgresql如何从孩子那里获得所有的父母(跟踪)



我得到了这样的表格:

id  | code    | code_parent | 
----|---------|------------ |
1  | 1       |   1         | 
2  | 2       |   2         | 
3  | 3       |   1         | 
4  | 4       |   3         |  
5  | 5       |   2         | 
6  | 6       |   4         | 
7  | 7       |   6         | 

我想返回一份所有家长的名单。示例:

select * from table where code 7

我想要这样的退货:

{1,3,4,6}

谢谢你的帮助。

您可以使用递归CTE:

with recursive cte as (
select code_parent, 1 as lev
from t
where code = 7
union all
select t.code_parent, lev + 1
from cte join
t
on cte.code_parent = t.code
where t.code <> t.code_parent
)
select code_parent as code
from cte;

如果你想要一个数组:

select array_agg(code_parent)
from cte;

这里有一个db<gt;不停摆弄

最新更新