在自引用表上编写递归SQL查询 [英] Writing a recursive SQL query on a self-referencing table

查看:48
本文介绍了在自引用表上编写递归SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

名称字段可用于构建指向项目的路径,方法是遍历每个父ID,直到它等于根项目‘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-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 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

这篇关于在自引用表上编写递归SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆