Get all parents for a child

后端 未结 3 1374
春和景丽
春和景丽 2020-12-14 16:50

I want to retrieve the parentid of an id, if that parentid has a parent again retrieve it, and so on. Kind of hierarchy table.

id----parentid
1-----1
5-----1         


        
相关标签:
3条回答
  • 2020-12-14 17:12

    you didn't mention the desired output and input. However you can try like this,

    Declare @t table (id int ,parentid int)
    insert into @t
    select 1,1 union all
    select 5,1 union all
    select 47894,5 union all
    select 47897,47894 
    
    ;With CTE as
    (
    select * from @t where id=1
    union all
    Select a.* from @t a inner join cte b
     on b.id=a.parentid and
    a.id<>b.id
    )
    select * from cte
    
    0 讨论(0)
  • 2020-12-14 17:14

    Your query is doing recursion but in opposite direction. So if you change starting point to:

    where id = 1
    

    then you will have user 1 and all his successors

    0 讨论(0)
  • 2020-12-14 17:16

    Try this to get all parents of a child

    ;with name_tree as 
    (
       select id, parentid
       from Users
       where id = 47897 -- this is the starting point you want in your recursion
       union all
       select C.id, C.parentid
       from Users c
       join name_tree p on C.id = P.parentid  -- this is the recursion
       -- Since your parent id is not NULL the recursion will happen continously.
       -- For that we apply the condition C.id<>C.parentid 
        AND C.id<>C.parentid 
    ) 
    -- Here you can insert directly to a temp table without CREATE TABLE synthax
    select *
    INTO #TEMP
    from name_tree
    OPTION (MAXRECURSION 0)
    
    SELECT * FROM #TEMP
    

    Click here to view result

    EDIT :

    If you want to insert into a table variable, you can do something like:

    -- Declare table varialbe
    Declare @TABLEVAR table (id int ,parentid int)
    
    
    ;with name_tree as 
    (
       select id, parentid
       from #Users
       where id = 47897 -- this is the starting point you want in your recursion
       union all
       select C.id, C.parentid
       from #Users c
       join name_tree p on C.id = P.parentid  -- this is the recursion
       -- Since your parent id is not NULL the recursion will happen continously.
       -- For that we apply the condition C.id<>C.parentid 
        AND C.id<>C.parentid 
    ) 
    -- Here you can insert directly to table variable
    INSERT INTO @TABLEVAR
    select *
    from name_tree
    OPTION (MAXRECURSION 0)
    
    SELECT * FROM @TABLEVAR
    

    Click here to view result

    0 讨论(0)
提交回复
热议问题