您能帮我为两个表编写递归查询吗?

时间:2019-03-26 10:34:22

标签: sql sql-server hierarchical-data recursive-query

我需要编写递归查询以查找此表中的所有子节点。

例如,我需要为ParentManagerTaskId = 6找到所有子ExecutorTasks

ManagerTasks
{
  Id,
  ParentExecutorTaskId
}

ExecutorTasks
{
  Id,
  ParentManagerTaskId
}



;WITH query AS 
 (
  SELECT et.Id,et.ParentManagerTaskId,mt.ParentExecutorTaskId
  FROM [Planning.ExecutorTasks] et
  left outer join [Planning.ManagerTasks] mt on et.ParentManagerTaskId=mt.Id
  WHERE mt.Id = 6
  UNION ALL      
  SELECT q.Id, q.ParentManagerTaskId,et.Id
  FROM [Planning.ExecutorTasks] et 
   JOIN query q ON et.Id = q.Id   
  )
  SELECT  *
  FROM query

1 个答案:

答案 0 :(得分:0)

您的模型有些误导,因为您有2个相互关联的表,并且只想显示其中一个的记录。这意味着您必须对递归部分进行2次联接才能获取相关实体的子代。

尝试以下操作:

;WITH Recursion AS
(
    -- Anchor
    SELECT
        ExecutorTaskId = E.Id,
        RecursionLevel = 0
    FROM
        [Planning.ExecutorTasks] AS E
    WHERE
        E.ParentManagerTaskId = 6

    UNION ALL

    -- Further childs
    SELECT
        ExecutorTaskId = E.Id,
        RecursionLevel = R.RecursionLevel + 1
    FROM
        Recursion AS R
        INNER JOIN [Planning.ManagerTasks] AS M ON R.ExecutorTaskId = M.ParentExecutorTaskId
        INNER JOIN [Planning.ExecutorTasks] AS E ON M.Id = E.ParentManagerTaskId
)
SELECT
    R.RecursionLevel,
    R.ExecutorTaskId
FROM
    Recursion AS R
ORDER BY
    R.RecursionLevel,
    R.ExecutorTaskId

我无法测试您是否未提供示例值,预期结果和表格的DDL。