2

I have a table describing elements organized in a tree-like structure:

ID, PARENT_ID, NAME  
0   null       TOP  
1   0          A  
2   0          B  
3   0          C  
4   1          AA  
5   2          BA 
6   3          CA  
7   6          CAA
...

There can be many levels in this hierarchy.

Suppose there is a list of elements (say IDs 2 and 3) for which I would like to get all child records from the table.

Something like this:

select *
from MY_TABLE 
start with PARENT_ID in (2,3)
connect by PARENT_ID = prior ID

will return:

ID, PARENT_ID, NAME 
5   2          BA
6   3          CA
7   6          CAA

However, I want the each output record to be mapped to the original parent from my list (2,3) so that the output would look like this:

ORIGINAL_PARENT_ID, ID, PARENT_ID, NAME 
2                   5   2          BA
3                   6   3          CA
3                   7   6          CAA

How can it be done?

4
  • 2
    What SQL engine are you using? MS SQL Server, MySQL, PL/SQL...? Also, won't 0 be the ORIGINAL_PARENT_ID for everything? Jan 4, 2013 at 16:26
  • I'm using PL/SQL. Yes, 0 would be the root element for everything, however I would like to start selecting chidren from the middle of the hierarchy, i.e. from elements 2 and 3 in my example. Since I start from 2 and 3, I see them as "original parents". Jan 4, 2013 at 16:35
  • @user1949013 shouldnt the last row in your example be original parent = 3?
    – DazzaL
    Jan 4, 2013 at 16:48
  • Yes, it should be 3 in the last row. Fixed that. Thanks. Jan 4, 2013 at 17:16

2 Answers 2

7

connect_by_root may be what you're after?

SQL> select t.*, connect_by_root parent_id as ORIGINAL_PARENT_ID
  2  from MY_TABLE  t
  3  start with PARENT_ID in (2,3)
  4  connect by PARENT_ID = prior ID
  5  /

        ID  PARENT_ID NAM ORIGINAL_PARENT_ID
---------- ---------- --- ------------------
         5          2 BA                   2
         6          3 CA                   3
         7          6 CAA                  3
0
0

Assuming your names are really as you have them, then the problem can be done without connect by. You can use simple string manipulation.

with ToFind (
    select 'C' as parent from dual union all
    select 'B' as parent from dual
   )
select t.*
from t join
     ToFind tf
     on t.name like tf.parent, 100)||'%' and t.name <> tf.parent
1
  • I used those names as an example. In my real data they can be anything. Thanks for suggestion. Jan 4, 2013 at 16:43

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.