如何查询(几乎)树结构

时间:2014-07-16 07:21:26

标签: sql database oracle

嗨,我得到了这张桌子:

id   replacement id
1     2
2     1
2     3
3     2
2     4
4     2
10    11
11    10

id(对象)采用树形结构,但是对于树结构,表的设计很差。 节点之间的连接是双向的。

确定一个人是否是另一个人的父亲的唯一方法是此表:

id  valid_until
1
2   2014-01-01
3   2013-01-01
4   2013-01-01
10  
11  2014-01-01

2是3和4的父级,因为它的valid_until晚于3和4. 1是顶级节点,因为它仍然有效。

我很难写这个数据的查询,所以看起来像这样:

id  parent
1
2   1
3   2
4   2 

有没有办法将其作为单个查询,或者我是否为此创建过程和临时视图?

编辑:我在表格中添加了一些新行。所以基本上我也想在查询中说我只想要id:1,2,3或4&#39树不是10和11.我该怎么做?

2 个答案:

答案 0 :(得分:1)

我相信这会有用

create table a (id number, rid number);

insert into a values(1,2);
insert into a values(2,1);
insert into a values(2,3);
insert into a values(3,2);
insert into a values(2,4);
insert into a values(4,2);

create table b (id number, d date);

insert into b values(1, null);
insert into b values(2, to_date('2014-01-01','yyyy-mm-dd'));
insert into b values(3, to_date('2013-01-01','yyyy-mm-dd'));
insert into b values(4, to_date('2013-01-01','yyyy-mm-dd'));

select aid id, case when adate = to_date('9999','yyyy') then null else rid end parent_id
from (
   select
     c.aid,
     c.rid,
     c.adate,
     nvl(b.d,to_date('9999','yyyy')) bdate 
   from (
         select a.id aid, a.rid rid, nvl(d,to_date('9999','yyyy')) adate 
         from a, b where a.id = b.id
         ) c, b 
          where c.rid = b.id
      ) where adate < bdate or adate = to_date('9999','yyyy')
order by id

答案 1 :(得分:1)

此答案回答了仅获取属于特定根节点的记录的后续问题:

select id, parent_id, level
from (
select aid id, case when adate = to_date('9999','yyyy') then null else rid end parent_id
from (select
   c.aid,
   c.rid,
   c.adate,
   nvl(b.d,to_date('9999','yyyy')) bdate from (select a.id aid, a.rid rid, nvl(d,to_date('9999','yyyy')) adate from a, b where a.id = b.id) c, b where c.rid = b.id
) where adate < bdate or adate = to_date('9999','yyyy')
) 
 START WITH id =1  -- ID of the ROOT node
connect by prior id = parent_id
order by id
相关问题