2012-08-07 2 views
4

의 부모 ID 찾는 방법 : 나는 특정 자식 ID의 첫 번째 ID를 찾으려면내가 다음 표했다 복귀 테이블

ID  ParentID 
1   NULL 
2   1 
3   2 
4   NULL 
5   4 
6   5 
7   3 

합니다. 예 : ID = 7이고 결과는 1
ID = 6이고 결과는 4

어떻게됩니까?

답변

4

이 문제를 해결하려면 재귀 적 CTE 마법을 수행해야합니다.

thusly 히 테이블 변수의 데이터 감안할 때 :

;with recursiveTable as 
(
    select d.id, d.parentId, 0 as depth 
    from @data d 
    where d.id=6 -- Parameterize this 
    union all 

    select d.id, d.parentid, r.depth-1 
    from @data d 
    inner join recursiveTable r 
    on d.id = r.parentId 
) 
select top 1 id 
from recursiveTable 
order by depth 

4을 반환 위와에서 6을 연결해 :

declare @data table(id int, parentid int) 
insert into @data 
    select 1, null 
    union select 2,1 
    union select 3,2 
    union select 4, null 
    union select 5,4 
    union select 6,5 
    union select 7,3 

다음은 트릭을해야 다음. 이 값을 7으로 변경하면 요청시 1을 반환합니다.

+1

을 그 것 때문에 * 훨씬 * 너무 간단합니다. ;) 솔루션에 대한 overthinking에 대해 이야기하고 답변을 업데이트하고 감사합니다! – Jamiec

0

이 시도 :

CREATE TABLE childpar(ID int,ParentID int) 
    INSERT INTO childpar 
    values(1,NULL), 
    (2, 1), 
    (3, 2), 
    (4, NULL), 
    (5, 4), 
    (6, 5), 
    (7, 3) 


DECLARE @inpyID int 
SET @inpyID=7 

;WITH CTE1 as (
select * from childpar where [email protected] 
union all 
select c2.* from CTE1 c1 inner join childpar c2 on c1.ParentID = c2.ID 
) 

select top 1 id from CTE1 order by id asc 
+0

저는 첫 번째 CTE의 요점을 보지 않으며, 아이보다 부모를위한 ID가 낮다고합니다. 이것은 OP를위한 경우지만 당신은 항상 그것이라고 생각할 수 thiink 해달라고! – Jamiec

+0

내가 실수로 코드 줄을 .. .. !! – AnandPhadke

+0

대답 수정 .Pls 점검 – AnandPhadke