我正在使用缺少递归 CTE 的 PADB/Postgres。我试图找到一种方法来编写递归自连接,仅使用常规连接/联合而不使用递归 CTE。最简单的方法是什么?
我有一个这样的表:
PersonID | Initials | ParentID
1 CJ NULL
2 EB 1
3 MB 1
4 SW 2
5 YT NULL
6 IS 5
而且我希望能够仅获取与从特定人员开始的层次结构相关的记录。因此,如果我通过 PersonID=1 请求 CJ 的层次结构,我将得到:
PersonID | Initials | ParentID
1 CJ NULL
2 EB 1
3 MB 1
4 SW 2
对于 EB,我会得到:
PersonID | Initials | ParentID
2 EB 1
4 SW 2
最佳答案
这是我能想到的最简单的解决方案。
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')
personid 需要替换为您需要查看其层次结构的人员。
SQL fiddle :http://sqlfiddle.com/#!15/f1201/1
关于sql - 没有 CTE 的 Postgres/PADB 中的递归自查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31857785/