首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用oracle-10g在层次查询中获取根祖先?

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

Stack Overflow用户
提问于 2013-03-24 06:36:00
回答 2查看 10.4K关注 0票数 5

表非常简单,pid表示父id,cid表示子id.And -- table.So中可能有多棵树--我的问题是:

了解几个i,如何才能得到根祖先?

下面是一个例子

pid

1 2

2 3

3 4

5 6

6 7

7 8

给定cid =4或cid = 8,我想得到它们的根祖先,其pid为1ro5。

最后,我使用的是oracle10g

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-24 06:42:31

代码语言:javascript
复制
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

小提琴

票数 4
EN

Stack Overflow用户

发布于 2017-07-24 16:43:51

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

代码语言:javascript
复制
| pid  | cid  |
|------*------|
| null |  2   |
|  2   |  3   |
|  3   |  4   |
| null |  6   |
|  6   |  7   |
|  7   |  8   |

因此,我建议使用这样的方法:

代码语言:javascript
复制
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;

小提琴

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15595850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档