简体   繁体   中英

Linq - select N-level childs from hierarchy parents

I have 2 tables as below:

Parent child relationship (table 1):

SourceId    SourceParentId

1     null

2      1

3      2

4      null


Items (Table 2):

Id       SourceId

1       1

2       1

3       2

4       2

5       3

6       4

How to write a linq query that return me all items based on Source ID? If my input is SourceId = 1, i will get items 1,2,3,4 & 5. If my input for sourceId is 2, i will get 3 items: 3, 4 & 5. If my input for sourceID is 4, it will return me item 6. My parent child is N-level and items can appear at any level. Help :(

Here try this

--Variable to hold input value
DECLARE @inputSourceID INT = 1;

--Recursive CTE that finds all children of input SourceID
WITH MyCTE
AS
(
SELECT SourceID,
        SourceParentID
FROM table1
WHERE SourceID = @inputSourceID
UNION ALL
SELECT  table1.SourceID, 
        table1.SourceParentID
FROM table1
INNER JOIN MyCTE 
    ON table1.SourceParentID = MyCTE.SourceID 
)

--Join the CTE with the table2 to find all id
SELECT table2.ID
FROM MyCTE
INNER JOIN table2
ON MyCTE.SourceID = table2.SourceID

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