【问题标题】:Writing a recursive SQL query on a self-referencing table在自引用表上编写递归 SQL 查询
【发布时间】:2012-10-21 08:25:38
【问题描述】:

我有一个数据库,其中包含一个名为 Items 的表,其中包含以下列:

  • ID - 主键,唯一标识符
  • 名称 - nvarchar(256)
  • ParentID - 唯一标识符

名称字段可用于构建项目的路径,方法是遍历每个 ParentId,直到它等于“11111111-1111-1111-1111-111111111111”,这是一个根项目。

所以,如果你有一个表格,里面有这样的行

ID                                   Name        ParentID
-------------------------------------------------------------------------------------
11111111-1111-1111-1111-111111111112 grandparent 11111111-1111-1111-1111-111111111111
22222222-2222-2222-2222-222222222222 parent      11111111-1111-1111-1111-111111111112
33333333-3333-3333-3333-333333333333 widget      22222222-2222-2222-2222-222222222222

因此,如果我在上面的示例中查找 ID 为“33333333-3333-3333-3333-333333333333”的项目,我想要路径

/grandparent/parent/widget 

返回。我试图写一个 CTE,因为看起来这就是你通常会如何完成这样的事情 - 但由于我不做很多 SQL,我无法完全弄清楚我哪里出错了。我查看了一些示例,这与我似乎能够得到的最接近 - 它只返回子行。

declare @id uniqueidentifier
set @id = '10071886-A354-4BE6-B55C-E5DBCF633FE6'
;with ItemPath as (
    select a.[Id], a.[Name], a.ParentID 
        from Items a
            where Id = @id

    union all

    select parent.[Id], parent.[Name], parent.ParentID 
        from Items parent 
            inner join ItemPath as a
                on a.Id = parent.id
                    where parent.ParentId = a.[Id]
)
select * from ItemPath

我不知道如何为路径声明一个局部变量并在递归查询中继续附加它。在此之后,我将尝试至少将所有行都发送给父级。如果有人也可以提供帮助,我将不胜感激。

【问题讨论】:

    标签: sql sql-server recursion common-table-expression


    【解决方案1】:

    这里是可行的解决方案

    SQL FIDDLE EXAMPLE

    declare @id uniqueidentifier
    set @id = '33333333-3333-3333-3333-333333333333'
    
    ;with ItemPath as 
    (
        select a.[Id], a.[Name], a.ParentID 
        from Items a
        where Id = @id
    
        union all
    
        select parent.[Id], parent.[Name] + '/' + a.[Name], parent.ParentID 
        from ItemPath as a
            inner join Items as parent on parent.id = a.parentID
    )
    select * 
    from ItemPath
    where ID = '11111111-1111-1111-1111-111111111112'
    

    我不太喜欢它,我认为更好的解决方案是换一种方式。等一下,我试着写另一个查询:)

    更新在这里

    SQL FIDDLE EXAMPLE

    create view vw_Names
    as
        with ItemPath as 
        (
            select a.[Id], cast(a.[Name] as nvarchar(max)) as Name, a.ParentID 
            from Items a
            where Id = '11111111-1111-1111-1111-111111111112'
    
            union all
    
            select a.[Id], parent.[Name] + '/' + a.[Name], a.ParentID 
            from Items as a
                inner join ItemPath as parent on parent.id = a.parentID
        )
    select * 
    from ItemPath
    

    现在你可以使用这个视图了

    declare @id uniqueidentifier
    set @id = '33333333-3333-3333-3333-333333333333'
    
    select * 
    from vw_Names where Id = @id
    

    【讨论】:

    • 当我尝试运行其中任何一个时,我收到此错误:Types don't match between the anchor and the recursive part in column "Name" of recursive query "ItemPath". 知道为什么吗?
    • 我能够通过将两个名称字段转换为 nvarchar(255) 来解决此问题,感谢所有帮助!
    • 是的,我认为在 CTE 视图的第一部分使用 nvarchar(max) 会更好,我已经更改了答案
    【解决方案2】:

    我需要这个答案的稍微不同的版本,因为我想生成树中所有谱系的列表。我还想知道每个节点的深度。我添加了一个可以循环访问的顶级父级临时表和一个用于构建结果集的临时表。

        use Items
    
        Select *
        Into   #Temp
        From   Items
        where ParentID=0
    
        Declare @Id int 
    
        create table #Results 
        (
            Id int,
            Name nvarchar(max),
            ParentId int,
            Depth int
        )
        While (Select Count(*) From #Temp) > 0
        Begin
            Select Top 1 @Id = Id From #Temp
            begin
                with ItemPath as 
                (
                    select a.[Id], cast(a.[Name] as nvarchar(max))as Name, a.ParentID ,1 as 
    Depth
                    from Items a
                    where a.ID = @id
    
                    union all
    
                    select a.[Id], parent.[Name] + '/' + a.[Name], a.ParentID, 1 + Depth
                    from Items as a
                        inner join ItemPath as parent on parent.id = a.parentID
                )
                insert into #Results
                select *
                from ItemPath
            end         
            Delete #Temp Where Id = @Id            
        End
        drop table #Temp           
        select * from #Results
        drop table #Results
    

    如果我们从下表开始...

    Id Name   ParentID
    1  Fred   0
    2  Mary   0
    3  Baker  1
    4  Candle 2
    5  Stick  4
    6  Maker  5
    

    我们会得到这个结果表。

    Id Name                    ParentID Depth
    1  Fred                    0        1
    2  Mary                    0        1
    3  Fred/Baker              1        2
    4  Mary/Candle             2        2
    5  Mary/Candle/Stick       4        3
    6  Mary/Candle/Stick/Maker 5        4
    

    【讨论】:

      猜你喜欢
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      相关资源
      最近更新 更多