Recursively find all ancestors given the child

后端 未结 1 1714
长发绾君心
长发绾君心 2020-12-14 10:28

Given a child id, I need to return a query containing all parents of that child as well as their parents till I get to the root parent. For example, given this data:

<
相关标签:
1条回答
  • 2020-12-14 11:00

    This is more or less what you want:

    -- CTE to prepare hierarchical result set
    ;WITH #results AS
    (
        SELECT  id, 
                parentid 
        FROM    [table] 
        WHERE   id = @childId
        UNION ALL
        SELECT  t.id, 
                t.parentid 
        FROM    [table] t
                INNER JOIN #results r ON r.parentid = t.id
    )
    SELECT  *
    FROM    #results;
    

    Reference:

    • CTE: Common Table Expression

    Working example:

    -- create table with self lookup (parent id)
    CREATE TABLE #tmp (id INT, parentid INT);
    
    -- insert some test data
    INSERT INTO #tmp (id, parentid) 
    SELECT 1,0 UNION ALL SELECT 2,1 UNION ALL SELECT 3,2
    UNION ALL SELECT 4,0 UNION ALL SELECT 5,3;
    
    -- prepare the child item to look up
    DECLARE @childId INT;
    SET @childId = 5;
    
    -- build the CTE
    WITH #results AS
    (
        SELECT  id, 
                parentid 
        FROM    #tmp 
        WHERE id = @childId
        UNION ALL
        SELECT  t.id, 
                t.parentid 
        FROM    #tmp t
                INNER JOIN #results r ON r.parentid = t.id
    )
    
    -- output the results
    SELECT  * 
    FROM    #results 
    WHERE   id != @childId 
    ORDER BY id;
    
    -- cleanup
    DROP TABLE #tmp;
    

    Output:

    1 | 0
    2 | 1
    3 | 2

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