簡體   English   中英

沒有CTE的Postgres / PADB中的遞歸自查詢

[英]Recursive self query in Postgres/PADB without CTEs

我正在使用缺少遞歸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')

人員標識需要替換為您需要查看其層次結構的人員。

SQL小提琴: http ://sqlfiddle.com/#!15/f1201/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM