gpt4 book ai didi

database - 如何使用 oracle-10g 在层次结构查询中获取根祖先?

转载 作者:太空狗 更新时间:2023-10-30 01:54:16 28 4
gpt4 key购买 nike

表很简单,pid表示父id,cid表示子id。表中可能不止一棵树。所以我的问题是:
知道几个 cid,我们怎样才能得到根祖先
这是一个例子

pid cid
1 2
2 3
3 4
5 6
6 7
7 8

给定 cid = 4 或 cid = 8,我想得到它们的 pid 为 1 ro 5 的根祖先
最后,我使用的是 oracle 10g

最佳答案

在数据库环境中,顶层的外键很可能是空值,如下所示:

| pid  | cid  |
|------*------|
| null | 2 |
| 2 | 3 |
| 3 | 4 |
| null | 6 |
| 6 | 7 |
| 7 | 8 |

所以我建议使用类似的东西:

select connect_by_root(t1.cid) as startpoint,
t1.cid as rootnode
from your_table t1
where connect_by_isleaf = 1
start with t1.cid in (8, 4)
connect by prior t1.pid = t1.cid;

fiddle

关于database - 如何使用 oracle-10g 在层次结构查询中获取根祖先?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15595850/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com