如何在sql中使用连接选择两个表父和子层次结构?

时间:2016-08-03 06:51:13

标签: sql-server

我尝试从两个不同的表中选择父子层次结构,但是没有得到正确的输出..如果有人知道告诉我..

Table1

Id      title     
1         a1
2         b   
3         c1
4         d1 

Table2

Id      title    pid
1         a     null
2         b         1
3         c         2
4         d         1

检查table1 id是否等于table2 pid然后获取table1标题。

输出

Id title
1     a1
2      a1<b    
3      a1<b<c1 
4       a1<d1

SELECT T2.PId AS MId, CASE WHEN T2.Id IS NOT NULL THEN T2.Title + '>' + T1. title ELSE T1. title END AS title, T2.Id AS PId 
FROM(SELECT T0.Id AS Id, CASE WHEN T1.Id IS NOT NULL THEN T1.Title + '>' + T0. title ELSE T0.title END AS title, T1.PId AS PId 
FROM (SELECT T1.PgeId AS MnuId, T1.Title  AS title, adnMNU.PId AS PId 
FROM TABLE1 T1 join TABLE2 ON T1.Id = TABLE2.Id ) T0
  Left JOIN adnPGE T2 ON T0.PId=T1.Id )T1
  Left JOIN adnPGE T3 ON T1.PId=T2.Id

1 个答案:

答案 0 :(得分:0)

我使用递归公用表表达式(CTE)。一个注意事项,看起来你并没有使用表2中的标题。只是一个观察;它并没有伤害我的感情。因此,我创建了一个使用Table2中的Ids和Table1中的标题的数据视图。

with Table1 as (
    select * from (values
        (1, 'a1'),
        (2, 'b '),  
        (3, 'c1'),
        (4, 'd1')
    ) as x(Id, title)
), Table2 as (
    select * from (values

        (1, 'a', null),
        (2, 'b', 1   ),
        (3, 'c', 2   ),
        (4, 'd', 1   )
    ) as x(Id, title, pid)
), combined as (
    select b.Id, a.title, b.pid
    from Table1 as a
    join Table2 as b
        on a.Id = b.Id
), r_cte as (

    select *, cast(title as varchar(max)) as [path]
    from combined
    where pid is null

    union all

    select child.*, cast(concat(parent.[path], '>', child.title) as varchar(max))
    from r_cte as parent
    join combined as child
        on child.pid = parent.Id
)
select * 
from r_cte
order by id;