I am using PADB/Postgres which lacks recursive CTE's. I am trying to find a way to write a recursive self join using only regular joins/unions without recursive CTEs. What is the simplest way to do this?
I have a table like this:
PersonID | Initials | ParentID
1 CJ NULL
2 EB 1
3 MB 1
4 SW 2
5 YT NULL
6 IS 5
And I want to be able to get the records only related to a hierarchy starting with a specific person. So If I requested CJ's hierarchy by PersonID=1 I would get:
PersonID | Initials | ParentID
1 CJ NULL
2 EB 1
3 MB 1
4 SW 2
And for EB's I'd get:
PersonID | Initials | ParentID
2 EB 1
4 SW 2
This is the simplest solution i can think of.
select * from t where personid = '1' --needs replacement with personid you run for
union
select * from t where personid in (select personid from t where parentid = '1')
or parentid in (select personid from t where parentid = '1')
The personid needs replacement with the person you need to see the hierarchy for.
SQL Fiddle: http://sqlfiddle.com/#!15/f1201/1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.