0

I have a table having parent child relationship :

Parent_id Child_id
1 2
1 5
2 3
2 4
5 6
7 4
7 8 
8 6

The relation is between child and immediate parent.

There can be multiple parents of a child like 4 is child of 2 and 7

How can I find the top most parent of a child using sql query?

EXAMPLE : for 3 the answer has to be 1

for 4 the answer can be 1 or 7. for simplicity lets assume I have to return the smallest one i.e 1

for 5 the answer is 1(because 1 is having no parent, so it will be considered topmost)

I am using DB2 (10.5) but a general sql query will give me the idea.

no one
  • 477
  • 6
  • 19

1 Answers1

0

a possibility in db2 (doesnt work on MySQL)

SELECT CHILD_ID, min(ROOT) as ROOT FROM (         
  SELECT CONNECT_BY_ROOT PARENT_ID AS ROOT, f1.* 
  FROM YOURTABLE f1                       
  CONNECT BY NOCYCLE PRIOR CHILD_ID=PARENT_ID     
) tmp                                         
group by CHILD_ID
Esperento57
  • 16,521
  • 3
  • 39
  • 45