how to get the root ancestors in a hierarchy query using oracle-10g?

会有一股神秘感。 提交于 2019-12-10 15:41:37

问题


the table is very simple,pid means the parent id,and cid means the child id.And there may be more than one trees in the table.So my question is:
knowing several cid,how can we get the root ancestors
here is an example

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

given cid = 4 or cid = 8,I want to get their root ancestors whose pid is 1 ro 5
finally,I'm using an oracle 10g


回答1:


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




回答2:


In a a database environment the foreign keys at the top level will most likely be nulls like so:

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

So I'd recommend using something like:

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



来源:https://stackoverflow.com/questions/15595850/how-to-get-the-root-ancestors-in-a-hierarchy-query-using-oracle-10g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!