我在SQL Server中有如下记录。
Id RefId FromRefId
1 RH01 RH00
2 RH02 RH01
3 RH03 RH01
4 RH04 RH03
5 RH05 RH02
6 RH06 RH03
7 RH07 RH04
8 RH08 RH02
9 RH09 RH05
我希望在条件
中使用Id获得如下结果Where Id=1
RH02
RH03
RH04
RH05
RH06
RH07
RH08
RH09
Where Id=2
RH05
RH08
RH09
Where Id=3
RH04
RH06
RH07
Where Id=4
RH07
Where Id=5
RH09
谢谢,请指导我如何实现这一目标?
答案 0 :(得分:0)
由于您希望获得FromRefId
链之后的所有引用,因此需要使用递归查询,这可以使用recursive common table expression在SQL Server中实现:
with Recursive_IDs (Id, RefId, FromRefId) as (
-- anchor query
select Id, RefId, FromRefId
from IDs
union all
-- recursive query
select IDs.Id, IDs.RefID, Recursive_IDs.FromRefId
from IDs
inner join Recursive_IDs on Recursive_IDs.RefId=IDs.FromRefId
)
select Recursive_IDs.RefId
from Recursive_IDs
join IDs on Recursive_IDs.FromRefID=IDs.RefID
where IDs.id = [the id you want]
请注意,如果您不是按Id
搜索,而是按RefId
进行搜索,则可以稍微简化一下查询:
with Recursive_IDs (Id, RefId, FromRefId) as (
-- anchor query
select Id, RefId, FromRefId
from IDs
union all
-- recursive query
select IDs.Id, IDs.RefID, Recursive_IDs.FromRefId
from IDs
inner join Recursive_IDs on Recursive_IDs.RefId=IDs.FromRefId
)
select Recursive_IDs.RefId
from Recursive_IDs
where FromRefId = [the RefId you want]
答案 1 :(得分:0)
您可以使用以下方法。我写了一个表值函数“GetChild”。它以递归方式遍历记录以获取所有依赖项,最后获取所有这些依赖项的RefId。
Create table hierarchy (Id int, RefId varchar(10), FromRefId varchar(10)) GO insert into hierarchy select 1,'RH01','RH00' union all select 2,'RH02','RH01' union all select 3,'RH03','RH01' union all select 4,'RH04','RH03' union all select 5,'RH05','RH02' union all select 6,'RH06','RH03' union all select 7,'RH07','RH04' union all select 8,'RH08','RH02' union all select 9,'RH09','RH05' GO -- Table valued Function GO create function GetChild (@Id INT) RETURNS @temp TABLE (RefId varchar(10)) AS BEGIN declare @tempDependencies table (Id int) insert into @tempDependencies SELECT @Id WHILE ((Select COUNT(Id) from hierarchy where FromRefId in (select RefId from hierarchy where id in (select Id from @tempDependencies) ) and id not in (select Id from @tempDependencies)) > 0) BEGIN insert into @tempDependencies Select Id from hierarchy where FromRefId in (select RefId from hierarchy where id in (select Id from @tempDependencies) ) and id not in (select Id from @tempDependencies) END insert into @temp Select RefId from hierarchy where FromRefId in (select RefId from hierarchy where id in (SELECT Id from @tempDependencies)) return END GO -- You may call the functions like this: select * from GetChild(1) select * from GetChild(2) select * from GetChild(3)
答案 2 :(得分:-1)
应该是一个简单的查询
SELECT * FROM your_table_name WHERE Id = your_desired_id
降级为什么?那不是你想要的吗?我认为你的问题不清楚。这里提到哪个ID?!