孩子ID父母ID概念

时间:2018-08-20 08:59:52

标签: sql postgresql hierarchical-data

源表是

TABLE 1     
ID  NAME    
X1  ssnnmm  

TABLE 2     
ID  NAME    LEVEL
Z1  ss      1
Z2  nn      2
Z3  mm      3

我想要以下结果

RESULT      
CHILD_ID    PARENT_ID   
X1          Z1  
Z1          Z2  
Z2          Z3  
Z3          NULL

基于表2的级别列

谢谢。

1 个答案:

答案 0 :(得分:0)

这将返回您指定的结果:

with t1 as (
      select 'X1'::text as id, 'ssnnmm' as name
     ),
     t2 as (
      select 'Z1'::text as id, 'ss' as name, 1::int as level union all
      select 'Z2' as id, 'nn' as name, 2::int as level union all
      select 'Z3' as id, 'mm' as name, 3::int as level
     )
select t2.id, t2p.id
from t2 left join
     t2 t2p
     on t2p.level = t2.level + 1
union all
select t1.id, t2.id
from t1  join
     t2
     on t2.level = 1;