通过 SQL 中的映射递归
Recurse through mappings in SQL
我有一个 table 这样的:
[Mappings]
Parent | Child
---------------
4 | 10
1 | 4
在 SQL 中,我正在尝试 运行 一个输入为 10
的查询,并取回链上的所有父项...所以 4
和 1
在这种情况下。
如果我 运行 输入 4
,它将 return 1
。
我想我需要使用一个通用的 table 表达式 (CTE),但语法让我失望。
我怀疑你使用 sql 服务器,如果是,那么你需要这样的东西:
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
在这种情况下)
我有一个 table 这样的:
[Mappings]
Parent | Child
---------------
4 | 10
1 | 4
在 SQL 中,我正在尝试 运行 一个输入为 10
的查询,并取回链上的所有父项...所以 4
和 1
在这种情况下。
如果我 运行 输入 4
,它将 return 1
。
我想我需要使用一个通用的 table 表达式 (CTE),但语法让我失望。
我怀疑你使用 sql 服务器,如果是,那么你需要这样的东西:
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
在这种情况下)