【问题标题】:T-SQL Recursive Query to show nested Tree structure显示嵌套树结构的 T-SQL 递归查询
【发布时间】:2022-03-09 10:05:20
【问题描述】:

我有以下 2 个表:

CREATE TABLE [Names] 
    (
    [Id] INT PRIMARY KEY,
    [Name] VARCHAR(100)
    )

CREATE TABLE [Relationships]
    (
    [Parent] [int] REFERENCES [Names]([Id]), 
    [Child] [int] REFERENCES [Names]([Id])
    )

Sample Data:

INSERT [NAMES] VALUES (1,'FRANK')
INSERT [NAMES] VALUES (2,'JO')
INSERT [NAMES] VALUES (3,'MARY')
INSERT [NAMES] VALUES (4,'PETER')
INSERT [NAMES] VALUES (5,'MAY')

INSERT [RELATIONSHIPS] VALUES (1,2)
INSERT [RELATIONSHIPS] VALUES (2,3)
INSERT [RELATIONSHIPS] VALUES (4,2)
INSERT [RELATIONSHIPS] VALUES (5,4)

如何显示名称的嵌套(树)列表,包括 [Id]、[Name] 和 [Level],其中 [Level] 表示从顶部开始的嵌套级别(Root:Level = 0;Root 的第一个子项:级别 = 1;等等……)? 例如,结果应该显示:

Level     Relationship
-----     ------------
2         FRANK <- JO
3         FRANK <- JO <- MARY
2         PETER <- JO
3         MAY <- PETER <- JO

【问题讨论】:

    标签: sql-server tsql recursion


    【解决方案1】:

    您可以考虑切换到Hierarchical Data。 TSQL 足够好地支持它,您不需要“重新发明轮子”。从长远来看,这将使您的查询更容易。

    Go here for a nice tutorial on the subject.

    【讨论】:

    • 你能确认 SQL 中的分层数据支持一个孩子的多个父母吗?
    • 分层数据仅支持每个孩子一个父母。见this form。如果您需要多父多子关系,该表单还包括一些其他选项
    【解决方案2】:

    试试这个:

    with Relatives as
    (
        select n.Id, cast(n.Name as varchar(max)) Relationship, 0 [Level]
        from Names n
        where not exists
        (
            select *
            from Relationships r
            where n.Id = r.Child
        )
    
        union all
    
        select n.Id, p.Relationship + ' <- ' + n.Name Relationship, p.[Level] + 1 [Level]
        from Names n
        join Relationships r
            on n.Id = r.Child
        join Relatives p
            on r.Parent = p.Id
    )
    
    select Relationship, [Level]
    from Relatives
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      相关资源
      最近更新 更多