Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tsql 如何递归地选择父元素下的所有子元素?_Tsql - Fatal编程技术网

Tsql 如何递归地选择父元素下的所有子元素?

Tsql 如何递归地选择父元素下的所有子元素?,tsql,Tsql,假设我们有一张桌子: WORKER NAME ID ManagerID ------------------------ John 1 3 Sally 2 3 Paul 3 4 Jane 4 5 Jennifer 5 8 约翰和莎莉为保罗工作,保罗为简工作 对于SQL查询,我希望向它提供Jane的ID(4),并让它返回她的所有下属: John 1 3 Sally

假设我们有一张桌子:

WORKER  
NAME     ID    ManagerID  
------------------------
John     1     3  
Sally    2     3  
Paul     3     4  
Jane     4     5  
Jennifer 5     8  
约翰和莎莉为保罗工作,保罗为简工作

对于SQL查询,我希望向它提供Jane的ID(4),并让它返回她的所有下属:

John     1     3  
Sally    2     3  
Paul     3     4
我还需要让这个查询递归地深入到所需的深度。例如,也许约翰有人为他工作,所以他们也会被包括在结果中



您将如何构建此查询

此页面显示如何使用TSQL将其组合在一起:


此页面显示如何使用TSQL将其组合在一起:


您可以使用简单的递归cte,如下所示:

;With cte as (
    Select * from YourWorker where ManagerId = 4

    union all

    select y.WorkerName, y.Id, y.ManagerId from YourWorker y inner join cte c
    on y.ManagerId = c.Id
)
select * from cte
+------------+----+-----------+
| WorkerName | Id | ManagerId |
+------------+----+-----------+
| Paul       |  3 |         4 |
| John       |  1 |         3 |
| Sally      |  2 |         3 |
+------------+----+-----------+
输出如下:

;With cte as (
    Select * from YourWorker where ManagerId = 4

    union all

    select y.WorkerName, y.Id, y.ManagerId from YourWorker y inner join cte c
    on y.ManagerId = c.Id
)
select * from cte
+------------+----+-----------+
| WorkerName | Id | ManagerId |
+------------+----+-----------+
| Paul       |  3 |         4 |
| John       |  1 |         3 |
| Sally      |  2 |         3 |
+------------+----+-----------+

您可以使用简单的递归cte,如下所示:

;With cte as (
    Select * from YourWorker where ManagerId = 4

    union all

    select y.WorkerName, y.Id, y.ManagerId from YourWorker y inner join cte c
    on y.ManagerId = c.Id
)
select * from cte
+------------+----+-----------+
| WorkerName | Id | ManagerId |
+------------+----+-----------+
| Paul       |  3 |         4 |
| John       |  1 |         3 |
| Sally      |  2 |         3 |
+------------+----+-----------+
输出如下:

;With cte as (
    Select * from YourWorker where ManagerId = 4

    union all

    select y.WorkerName, y.Id, y.ManagerId from YourWorker y inner join cte c
    on y.ManagerId = c.Id
)
select * from cte
+------------+----+-----------+
| WorkerName | Id | ManagerId |
+------------+----+-----------+
| Paul       |  3 |         4 |
| John       |  1 |         3 |
| Sally      |  2 |         3 |
+------------+----+-----------+