从Oracle的“开始于”和“连接依据”到Postgres

时间:2019-05-07 06:00:04

标签: sql postgresql recursive-query

UPD:

我要转换此Oracle代码:

select lpad(c4, length(c4) + (level*2)-2 , ' '), lpad(c2, length(c2) + (level*2)-2 , ' ')
from (select root_id c1, root_tab_col_name c2, null c3, 'root_table' c4 from root_table
    union all
    select second_tab_id, second_tab_col_name, root_tab_id, 'second_table' from second_table
    union all
    select third_tab_id, third_tab_col_name, second_tab_id, 'third_table' from third_table)
start with c3 is null
connect by prior c1 = c3;

至PostgreSQL形式。有人可以帮我吗?问候。

UPD:

我有3个与外键关联的表:

enter image description here

enter image description here

enter image description here

此查询的结果

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试:

with request_base as (
       select root_id c1, root_tab_col_name c2, null c3, 'root_table' c4 from root_table
    union all
       select second_tab_id, second_tab_col_name, root_tab_id, 'second_table' from second_table
     union all
    select third_tab_id, third_tab_col_name, second_tab_id, 'third_table' from third_table
)
,req2 as (WITH recursive recurs1(tables_name,texts,n) as (
      select c4,c2,c1 rel from request_base where c3 is null
    UNION 
        select c4,c2,c1 from request_base,recurs1 where c3=n
 )
    select tables_name,texts from recurs1
)
select * from req2