简体   繁体   中英

How to query a (almost) tree structure

Hi I got this table:

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

The id(objects) are in a tree structure but the table is designed poorly for a tree structure. The connection between the nodes goes both ways.

The only way to determine if one is the parent of another is this table:

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

2 is parent of 3 and 4 because its valid_until is later than 3 and 4. 1 is top node because it's still valid.

I'm struggling to write a query of this data so it could look like this:

id  parent
1
2   1
3   2
4   2 

Is there a way to make this as a single query or do I've to create a procedure and a temporary view for this?

EDIT: I added some new rows to my table. So basically I also want to say in the query that I only want id: 1,2,3 or 4's tree not 10 and 11. How do I do that?

I believe this will work

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

This answer answers the follow up question of only getting the records that belongs to a particular root node:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM