sql - 没有 CTE 的 Postgres/PADB 中的递归自查询

标签 sql postgresql recursive-query self-join

我正在使用缺少递归 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/

相关文章:

sql - knex插入多行

postgresql - Mountain Lion 中缺少套接字文件 "/var/pgsql_socket/.s.PGSQL.5432"(OS X 服务器)

sql - 基于邻接表递归查询分层数据

mysql - 递归动态查询

python - Django ORM - 具有两列的左外连接?

mysql - 使用 SQL 更新数据库中的数据

sql - 如果存在排序依据 (SQL Server)

postgresql - Postgres : using previous row value when current row value is null

database - 将列添加到表和 View 时锁定

mysql如何查找相对于父行的子行总数