如何在PostgreSQL中获得顶级父母

发布于 2025-02-03 21:27:50 字数 752 浏览 1 评论 0原文

我的桌子,父母和孩子有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

同尘 2025-02-10 21:27:50

您可以将顶级父母放在单独的专栏中

with recursive rcte as(
  select PARENT top, PARENT, CHILD
  from table1 t1
  where not exists (select 1 from table1 t2 where t1.parent = t2.child)

  union all

  select top, p.PARENT, p.CHILD
  from rcte 
  join table1 p on p.parent = rcte.child
)
select * 
from  rcte
order by top, parent;

You can keep top parent in a separate column

with recursive rcte as(
  select PARENT top, PARENT, CHILD
  from table1 t1
  where not exists (select 1 from table1 t2 where t1.parent = t2.child)

  union all

  select top, p.PARENT, p.CHILD
  from rcte 
  join table1 p on p.parent = rcte.child
)
select * 
from  rcte
order by top, parent;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文