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.