2013-10-17 60 views
0

我有一個名爲Project,其中父子關係是存儲的表。 parentprojectid列中的條目意味着相應的項目實例是一個孩子。是 表的列如下:PostgreSQL的遞歸排序

projectid, parentprojectid 

當我運行在該表上一個SELECT查詢,得到的數據應該由每一個父母,然後它的所有兒童(和其子女的子女,如果適用)。我如何實現這一目標?

這裏是什麼樣的數據看起來像一個例子:

 
projectid parentprojid 
proj1  null 
proj11  proj1 
proj12  proj1 
proj121 proj12 
proj2  null 
proj3  null 

回答

0

使用recursive common table expression,排序結果數組將所有的父母到數組,然後:

with recursive cte as (
    select t.projectid, t.parentprojid, array[t.projectid::text] as path 
    from Table1 as t 
    where t.parentprojid is null 
    union all 
    select t.projectid, t.parentprojid, c.path || t.projectid::text 
    from Table1 as t 
     inner join cte as c on c.projectid = t.parentprojid 
) 
select projectid, parentprojid 
from cte 
order by path 

sql fiddle demo

+0

@a_horse_with_no_name據我所見,「投射」 '已經是文本(VARCHAR實際上) –

+0

@a_horse_with_no_name是的,我試圖找到前意識到這'name'是'id' :) –

+0

一段時間數字'id'背後是什麼路徑列轉換爲宗旨一個數組,當查詢運行正常,即使沒有轉換爲數組? – Prmk