I have the following query:
select * from (
select p1.c as child, p1.p as parent, 1 as height
from parent as p1
where (p1.c=3 or p1.c=8);
union
select p2.c as child, p2.c as parent, 2 as height
from parent as p2
where (p1.child=3 or p1.child=8) and p1.parent = p2.child;
)
The schema is:
CREATE TABLE parent(p int, c int);
I'm trying to find a path from the child to the root. [Edit] And append the number of edges we have to traverse.
The goal is to join the child's parent with its parent, something like:
(8, 2, 1)
(8, 5, 2) -> 8 is the lowest child, 2 is its parent, and 5 it's 2 parent.
Some sample data:
10 | 5
10 | 12
12 | 3
12 | 4
4 | 6
4 | 7
5 | 11
5 | 2
2 | 8
How can I use the reference for the first query p1
inside the second query that will form p2
?
After that I should have;
(8,2,1)
(3,12,1)
(3,10,2)
(8,5,2)
Thus I already will know what to do to complete what I want.