FK在同一张桌子上

时间:2010-10-05 13:07:41

标签: sql tsql

我有ID的表是PK,我在同一个表列中有ParentID,在某些情况下是ID的。(我说有些情况,因为例如ParentID可以是0,但ID不在ID的列中)。 我尝试创建Query:

ID     ParentID     Value
1      0            Test
2      0            Test01
3      2            Test02
4      3            Test03

当我发送ID = 4时,我需要这个结果:

ID     ParentID     Value
2      0            Test01
3      2            Test02
4      3            Test03

任何帮助......

3 个答案:

答案 0 :(得分:1)

请勿使用0(零)但null表示“没有父母在场”。

答案 1 :(得分:1)

这对我来说看起来像一个树遍历问题,这对于基于集合的操作来说并不是特别适合。以下是有效的,但它并不太优雅:

-- turn this into stored proc?
declare @inputId int
set @inputId = 4


declare @Ids table (ID int)
insert into @Ids values (@inputId)

declare @reccount int
set @reccount = 1
declare @lastreccount int
set @lastreccount = 0
while @reccount <> @lastreccount
begin
    set @lastreccount = @reccount
    insert into @Ids 
        select ParentID from recursiveTest 
            where ID in (select ID from @Ids)
                and ParentID not in (select ID from @Ids)
    set @reccount = (select COUNT(*) from @Ids)                      
end

select * from recursiveTest where ID in (select ID from @Ids);

答案 2 :(得分:0)

试试这个:

Declare @Id Integer Set @Id = 4
With Child(Id, ParentId, Value, Level) As
  ( Select Id, ParentId, Value, 0 as Level
    From table 
    Where id = @Id
    Union All
    Select t.Id, t.ParentId, t.Value, level + 1
    From Child c Join table t 
       On t.Id = c.ParentId
  )
Select id. ParentId, Value, Level
From Child
Order By Id