如何在PostgreSQL中获得顶级父母
我的桌子,父母和孩子有2列。我想为每一行获得顶级父母。我拥有的数据在下面有些提及。
PARENT CHILD
A01 B01
A01 C01
B01 D02
B01 E02
C01 F02
X01 Y01
Y01 Z02
Z02 D02
然后,我希望我知道
TOP PARENT PARENT CHILD
A01 A01 B01
A01 A01 C01
A01 B01 D02
A01 B01 E02
A01 C01 F02
X01 X01 Y01
X01 Y01 Z02
X01 Z02 D02
我知道在Oracle sys_connect_by_path 中有一个功能,我可以用它来获得任何层次结构的路径和最高父母,但不确定如何在PostgreSQL中做。谁能指导我,或者只是给我一个提示?
不知道这是否有帮助,但这就是我到目前为止一直在尝试的
with recursive cte as (
select br2."PARENT" , br2."CHILD"
from table1 br2
inner join cte on cte."PARENT" = br2."CHILD"
)
select * from cte
I have 2 columns in a table, Parent and Child. I want to get Top Parent for each row. The data I have is somewhat mentioned below.
PARENT CHILD
A01 B01
A01 C01
B01 D02
B01 E02
C01 F02
X01 Y01
Y01 Z02
Z02 D02
Then result I am expecting is
TOP PARENT PARENT CHILD
A01 A01 B01
A01 A01 C01
A01 B01 D02
A01 B01 E02
A01 C01 F02
X01 X01 Y01
X01 Y01 Z02
X01 Z02 D02
I know there is a function in Oracle SYS_CONNECT_BY_PATH which I can use to get the path and Top Parent of any hierarchal structure but not sure how to do in Postgresql. Can anyone guide me or just maybe give me a hint to start with ?
Not sure if this is helpful but that's what I've been trying so far
with recursive cte as (
select br2."PARENT" , br2."CHILD"
from table1 br2
inner join cte on cte."PARENT" = br2."CHILD"
)
select * from cte
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将顶级父母放在单独的专栏中
You can keep top parent in a separate column