写完整的从属链

时间:2016-09-21 18:38:07

标签: sql sql-server join common-table-expression self-join

我有以下学生表

id  boss_id name    age
1   NULL    NEW_A   10
2   1       NEW_A   12
3   1       NEW_A   14
4   3       NEW_A   16
5   3       NEW_A   18
6   5       NEW_A   20
7   1       NEW_B   22
8   1       NEW_B   24
9   8       NEW_B   26
10  9       NEW_B   28
11  4       NEW_B   44

以下查询

select s.id as student, boss.id as boss from Student s, Student boss
where s.boss_id = boss.id --and s.id = 11
order by s.id

检索

2   1
3   1
4   3
5   3
6   5
7   1
8   1
9   8
10  9
11  4

我想要返回完整的链从属

例如对于学生11应该是

student_id    boss_id
11              4
4               3
3               1

sql是否允许根据我的需要编写查询?

1 个答案:

答案 0 :(得分:2)

您可以使用递归CTE执行此操作:

;With Cte As
(
    Select  T.id, T.boss_id
    From    YourTable   T
    Where   T.Id = 11
Union All
    Select  T.id, T.boss_id
    From    YourTable   T
    Join    Cte         C   On  C.boss_id = T.id
                            And T.boss_id Is Not Null
)   
Select  id, boss_id
From    Cte
id  boss_id
11  4
4   3
3   1

SQL Fiddle Live Demo