【问题标题】:how to get the root ancestors in a hierarchy query using oracle-10g?如何使用 oracle-10g 在层次结构查询中获取根祖先?
【发布时间】:2013-03-13 19:34:03
【问题描述】:
表很简单,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
【问题讨论】:
标签:
database
oracle
tree
oracle10g
root
【解决方案1】:
在数据库环境中,顶层的外键很可能是空值,如下所示:
| 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
【解决方案2】:
select
t1.cid,
connect_by_root(t1.pid) as root
from
your_table t1
left join your_table t2
on t2.cid = t1.pid
where t1.cid in (4, 8)
start with t2.cid is null
connect by t1.pid = prior t1.cid
fiddle