[英]Recursive self query in Postgres/PADB without CTEs
I am using PADB/Postgres which lacks recursive CTE's. 我正在使用缺少递归CTE的PADB / Postgres。 I am trying to find a way to write a recursive self join using only regular joins/unions without recursive CTEs.
我试图找到一种方法来编写仅使用常规联接/联合而没有递归CTE的递归自联接。 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 = 1请求CJ的层次结构,则会得到:
PersonID | Initials | ParentID
1 CJ NULL
2 EB 1
3 MB 1
4 SW 2
And for EB's I'd get: 对于EB,我会得到:
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 SQL小提琴: http ://sqlfiddle.com/#!15/f1201/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.