2017-06-01 78 views
0

映射我有一个这样的表:通过递归在SQL

[Mappings] 

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

在SQL中,我试图运行与10输入查询,并取回其父母的全部环比上涨。在这种情况下41

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

我在想我需要使用一个公共表格表达式(CTE),但是语法却把我抛弃了。

+0

什么RDBMS也许有用吗?该语言可以是具体的 – xQbert

+1

它的答案在这里: [https://stackoverflow.com/questions/28170635/get-all-parents-for-a-child](https://stackoverflow.com/questions/28170635/get -all-parents-for-a-child) –

+0

这是SQL Server – mariocatch

回答

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)级列