【问题标题】:Recurse through mappings in SQL通过 SQL 中的映射进行递归
【发布时间】:2017-11-02 20:44:15
【问题描述】:

我有一张这样的桌子:

[Mappings]

Parent | Child
---------------
   4   |   10
   1   |   4

在 SQL 中,我试图运行一个输入为 10 的查询,并在链上取回它的所有父项...所以在这种情况下是 41

如果我使用4 的输入运行它,它将返回1

我在想我需要使用公用表表达式 (CTE),但语法让我失望。

【问题讨论】:

标签: sql hierarchical-data recursive-query


【解决方案1】:

我怀疑你使用 sql server,如果是,那么你需要这样的东西:

create table #test(
Parent int,
Child int
);

insert into  #test
values
(4   ,   10),
(1   ,   4),
(10   ,   12);

with rec as (
    select #test.*, 1 as lvl from #test where Child = 10
    union all
    select #test.*, lvl + 1 as lvl from #test    
    inner join rec   
    on #test.Child = rec.Parent
)
select parent, lvl from rec
OPTION (MAXRECURSION 0)

查看级别列也可能有用(在这种情况下为lvl

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2023-01-18
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多