Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

sql - Getting all the children of a parent using MSSQL query

I have the following data in my database:

Parent      Child
101         102
101         103
101         104
101         105
101         106

My parameter is 106. And using the parameter I want to retrieve all the other children under its parent which is 101. I tried using the recursive method but it didn't work given the following data. Is there another way to formulate a query?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you want to get siblings of the value @p0, you can use a simple self-join:

SELECT p.Child
FROM Table1 c
INNER JOIN Table1 p ON c.Parent = p.Parent
WHERE c.Child = @p0
AND p.Child <> @p0

The not-equal clause here makes sure you get siblings not including the value you searched for. Remove it as necessary.

SQL Fiddle example


Since you mention recursion though, perhaps you want the entire tree starting at the parent of the value @p0. In which case, you can use a recursive CTE:

WITH parent AS (
    SELECT Parent
    FROM Table1
    WHERE Child = @p0
), tree AS (
    SELECT x.Parent, x.Child
    FROM Table1 x
    INNER JOIN parent ON x.Parent = parent.Parent
    UNION ALL
    SELECT y.Parent, y.Child
    FROM Table1 y
    INNER JOIN tree t ON y.Parent = t.Child
)
SELECT Parent, Child
FROM tree

SQL Fiddle examples using your data and with additional data to demonstrate the recursive CTE


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...