【问题标题】:Sql Hierarchy loop querySql Hierarchy 循环查询
【发布时间】:2013-08-25 08:38:18
【问题描述】:

此表表示类别层次结构,层次结构顶部的元素的父 ID 为 NULL。表格如下:

**categoryId categoryName parentId**

1           Home         NULL
.           .            .
.           .            .
20          Vehicles      1
.           .           .
35          SUV          20
36          Motorbikes   20
.            .           .
90          BMW          35
91          Toyota       35
.            .           .
234         LandCruiser  91 

Home>Vehicles>SUV>Toyota>LandCruiser

我要做的是建立一个 sql 查询,它将返回我:

[categoryId],[categoryName] 任何给定 [categoryId] 的链。它应该循环并获取每一行,直到到达 parentId==NULL 的行。

如上例234->91->35->20->1->NULL(STOP)

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    你可以使用递归 cte:

    with cte as (
       select
          t.categoryId, t.categoryName, t.parentId,
          cast(t.categoryId as nvarchar(max)) as path
       from categories as t
       where t.categoryId = 234
    
       union all
    
       select
          c.categoryId, c.categoryName, t.parentId,
          c.path + '->' + cast(t.categoryId as nvarchar(max))
       from categories as t
           inner join cte as c on c.parentId = t.categoryId
    )
    select categoryid, categoryname, path + '->NULL'
    from cte
    where parentid is null
    

    sql fiddle demo

    【讨论】:

    • 应该有一个输入,例如,当我们将输入作为 234 时,查询应该返回父级列表,直到它到达 parentId 为空的父级。我试过但想不通修改它。感谢回复
    猜你喜欢
    • 1970-01-01
    • 2012-09-18
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多