简体   繁体   中英

Sql query for 3 level tree?

I have table and I want get 3 lvl tree. Example

Node
Id     ParentId     Name
 1       -1       Test 1
 2       -1       Test 2
 3        1       Test 1.1
 4        1       Test 1.2
 5        3       Test 1.1.1
 6        3       Test 1.1.2
 7        5       Test 1.1.1.1

If I filtered ParentId = -1 I want get rows ParentId = -1 and children's +2 lvl.

If I filtered Id = 2 I want get row Id = 2 and children's +2 lvl.

UPDATE

I use MS SQL Server 2008, Entity Framework 6.1.3. I understand, I can use 3 selects. But I looking effective method

You can use recursive SQL to do this in SQL server.

WITH recCTE (childID, parentID, Name, Depth) Assuming
(
    Select
        yourTable.id as childid,
        yourTable.parentID,
        CAST('Test ' + yourTable.id as varchar(20)) as Name
        0 as Depth
    FROM
        yourTable
    WHERE
        parentID = -1

    UNION ALL

    Select
        yourTable.id as childID,
        yourTable.ParentID as ParentID,
        recCTE.path + '.' + yourTable.id AS Name
        recCTE.depth + 1 as Depth
    FROM
        recCTE
        INNER JOIN yourTable on
        recCTE.childID = yourTable.parentID
    Where
        recCTE.Depth + 1 <= 2
)

SELECT * FROM recCTE;

The bit inside the CTE on top of the UNION is your seed query for the recursive sql. It's the place where your recursive lookup will start. You wanted to start at parentID = -1 , so it's here in the WHERE statement.

The bit inside the CTE below the UNION is the recursive term. This joins the recursive CTE back to itself and brings in more data from your table. Joining the id from your table to the childID from the recursive resultset.

The recursive term is where we test to see how deep we've gotten. If the Depth from the CTE + 1 is less than or equal to 2 then we stop adding children to the loop up, ending the loop for that particular leg of the hierarchy.

The last little bit below the CTE is just the part that runs the CTE so you get results back.

These recursive queries are confusing as hell at first, but spend some time with them and you'll find a lot of use for them. You'll also find that they aren't too difficult to write once you have all the parts sussed out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM