1

Table "links" contains 2 columns : PARENT_CODE, CHILD_CODE

PARENT_CODE | CHILD_CODE 
------------|------------
A1          | B1 
A1          | B2
B1          | C1 
B1          | C2 
B2          | C3 
B3          | C3
C3          | D1

This table eventually used to form following graph :

node structure

My question will be how to write optimized hierarchy query in Oracle to get the full graph connected, and the input parameter will be any of node.

To illustrate the input/output, this is simplified SQL : SELECT PARENT_CODE,CHILD_CODE FROM {HIERARCHY QUERY} where NODE = {ANY NODE}

2
  • I know there's hierarchical query in oracle, but it will not give all connected node.
    – NoodleX
    Apr 8, 2016 at 2:34
  • You can use connect by to do this. Select parent_code, child_code, level from links connect by prior child_code = parent_code. It will do a left tree walk and also provide a pseudo column with the level (depth) that it is currently evaluating. To make this work with any performance at all, both columns must be indexed (independently). WHOOPS - if B3 is not a child of A1, this breaks.
    – T Gray
    Apr 8, 2016 at 4:00

1 Answer 1

0

The query below with show you all links. The idea is that first I create two ways connection between nodes. Using it we can do recursive query that returns our results. The last thing is decode that returns who is real parent and who is child basing on dir (0 - means original direction, 1 - means reverted direction).

with linkT (parent_code, child_code) as 
(select 'A1','B1' from dual union all
 select 'A1','B2' from dual union all
 select 'B1','C1' from dual union all
 select 'B1','C2' from dual union all
 select 'B2','C3' from dual union all
 select 'B3','C3' from dual union all
 select 'C3','D1' from dual union all
 select 'E1','F1' from dual ),
T1 as (
select parent_code, child_code, 0 Dir from linkT
union all 
select child_code, parent_code, 1 Dir from linkT )
select distinct 
       decode(dir, 0, parent_code, child_code) as Parent_code,
       decode(dir, 0, child_code, parent_code) as Child_Code
from (
select parent_code, child_code, dir
from T1 x
start with x.child_code='A1'
connect by nocycle prior x.parent_code=x.child_code ) 
order by 1,2  
1
  • This is brilliant and exactly what I needed !
    – NoodleX
    Apr 8, 2016 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.