SQL Server递归层次结构查询

时间:2015-08-28 17:32:23

标签: sql sql-server recursive-query

这适用于SQL Server 2012.我需要生成一个包含链接的数据集,以及给定下表中给定起始ParentId的所有链接链接

CREATE TABLE Relations (
    Id INT NOT NULL PRIMARY KEY,
    ParentId INT NOT NULL,
    ChildId INT 
);

因此对于以下数据集:

1 A B
2 B C
3 C D
4 F D
5 F G
6 X Y
7 Y Z

从C开始,我希望得到第1到第5行,因为它们通过父层次结构或子层次结构全部链接到C。例如。 G有父F,它是D的父,是C的孩子。

它不是标准的层次结构查询,因为没有真正的根,我需要在两个方向上获得链接。所以这意味着我无法使用CTE递归技巧。这是我的尝试:

--Hierarchical Query using Common Table Expressions 
WITH ReportingTree (Id, Parent, Child, Lvl) 
AS 
( 
    --Anchor Member 
    SELECT Id,
     ParentId,
     ChildId,
   0 as Lvl
FROM Relations WHERE ParentId = 9488 
UNION ALL 
--Recusive Member 
SELECT 
 cl.Id,
 cl.ParentId,
 cl.ChildId,
 r1.Lvl+1 
FROM [dbo].[CompanyLinks] cl 
    INNER JOIN ReportingTree r1 ON ReportingTree.Parent = cl.Child
    INNER JOIN ReportingTree r2 ON cl.FromCompanyId = r2.Parent  <-- errors
) 
SELECT * FROM ReportingTree

我的第二次尝试涉及临时表和while循环。这可行,但结果非常缓慢:

BEGIN   
CREATE TABLE #R (
    Id INT NOT NULL PRIMARY KEY NONCLUSTERED,
    ParentId INT NOT NULL,
    ChildId INT 
);

CREATE CLUSTERED INDEX IX_Parent ON #R (ParentId);
CREATE INDEX IX_Child ON #R (ChildId);

INSERT INTO #R
  SELECT Id,ParentId ChildId
    FROM Relations
    WHERE ParentId = 9488 OR ChildId = 9488;
WHILE @@RowCount > 0
BEGIN
  INSERT INTO #R
    SELECT cl.Id,cl.ParentId, cl.ChildId
      FROM #R INNER JOIN
        Relations AS cl ON cl.ChildId = #R.ChildId OR cl.ParentId = #R.ParentId OR cl.ChildId = #R.Parent OR cl.ParentId = #R.Child
    EXCEPT
    SELECT Id,ParentId, ChildId
      FROM #R;  
END

SELECT * FROM Relations cl inner Join #Relations r ON cl.Id = #R.Id
DROP TABLE #R

END

有人可以建议一个可行的解决方案吗?

1 个答案:

答案 0 :(得分:3)

我们根据父ID和子ID的每个组合将每一行与每一行匹配,并沿途保存路径。递归地我们做这个匹配并创建路径,为了避免无限循环,我们检查路径是否先前没有遍历,最后我们有所有节点都有到所需节点的路径(@Id):

WITH cte AS ( 
        SELECT CompanyLinks.*, cast('(' + cast(ParentId as nvarchar(max)) + ',' 
                 + cast(ChildId as nvarchar(max))+')' as nvarchar(max)) Path 
          FROM CompanyLinks 
          WHERE ParentId = @Id OR ChildId = @Id
          UNION ALL 

          SELECT a.*,
               cast(
                     c.Path + '(' + 
                     cast(a.ParentId as nvarchar(max)) + ',' + 
                     cast(a.ChildId as nvarchar(max)) + ')' 
                   as nvarchar(max)
                   ) Path 
        FROM CompanyLinks a JOIN cte c ON 
              a.ParentId = c.ChildId 
              OR c.ParentId = a.ChildId 
              OR c.ParentId = a.ParentId 
              OR c.ChildId = a.ChildId 
            where c.Path not like cast(
                     '%(' + 
                     cast(a.ParentId as nvarchar(max)) + ',' + 
                     cast(a.ChildId as nvarchar(max)) + 
                     ')%' 
                   as nvarchar(max)
                   )

)
SELECT DISTINCT a.id, Company.Name, path from (
   SELECT distinct ParentId as id, path FROM cte
   union all 
   SELECT distinct ChildId as id, path FROM cte
) a inner join Company on Company.Id = a.Id

这是fiddle。 如果你想要不同的节点,只需使用:

SELECT DISTINCT id from (
   SELECT distinct ParentId as id FROM cte
   union all 
   SELECT distinct ChildId as id FROM cte
) a 

在查询结束时。

此查询实际上是无方向图上的广度优先搜索。

注意:基于Hogan注释,不需要检查路径,因为关系表中有一个主键(我没注意到)我们可以查找主键在先前的递归中,以避免无限循环。