Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting all parents in the order of relation from hierarchical table SQL

I've a table like this with a parent child relation in the same table

AccountID|     ParentID     |   AccountName
----------------------------------------------
1       |   0       |   Root
2       |   1       |   Child1
3       |   1       |   Child2
4       |   2       |   Child3
5       |   4       |   Child1
6       |   5       |   Child1
7       |   6       |   Child1
8       |   6       |   Child1

So when I send the account ID 7 I have to get the tables in the order like child,father,grandfather.. that way.. So for 7, I need to get all parets like this

AccountID
---------
    7
    6
    5
    4
    2
    1

So the most important point is the order. It should be from the bottom level to its next higher then to the next...

like image 598
Sandeep Thomas Avatar asked Aug 30 '13 07:08

Sandeep Thomas


People also ask

How do you query a parent child relationship in SQL?

To find out who that child's parent is, you have to look at the column parent_id , find the same ID number in the id column, and look in that row for the parent's name. In other words, Jim Cliffy has no parents in this table; the value in his parent_id column is NULL .

How do you query a hierarchy in SQL?

The anchor member of the CTE is the first SELECT statement. By doing this, you select the root of the hierarchy; it's the basis on which the recursive query will work its magic and find all other levels of the hierarchy. This statement selects all the columns from the table employee .


1 Answers

You can use a recursive CTE:

declare @childAccID int
set @childAccID = 7  

;WITH Rec_CTE 
    AS(
        SELECT 1 AS Level, 
               tChild.*
        FROM dbo.TableName tChild
        WHERE tChild.AccountID = @childAccID

        UNION ALL

        SELECT Level + 1 AS Level, 
               parent.*
        FROM Rec_CTE tParent
        INNER JOIN  dbo.TableName parent 
          ON parent.AccountID = tParent.ParentID
    )
SELECT * FROM Rec_CTE
ORDER BY Level

DEMO

like image 111
Tim Schmelter Avatar answered Oct 28 '22 12:10

Tim Schmelter