I need help with a sql query, I have tried to replicate my actual problem by creating this simple example:
Parents table:
id name parent_id
1 parent1 null
2 parent2 1
3 parent3 1
4 parent4 3
5 parent5 3
6 parent6 5
7 parent7 5
Relatives table:
id name parent_id
1 relative1 2
2 relative2 3
3 relative3 4
4 relative4 5
5 relative5 7
Parents table has a list of parents which also have parents themselves. Relatives table has a list of relatives with a parent_id column.
How would I find all the relatives of parent3 including all the 'desendants' of parent3, ie the query should return the following from the Relatives table:
relative2 (because the parent id is 3)
relative3 (because the parent id is 4 whose parent id is 3)
relative4 (because the parent id is 5 whose parent id is 3)
relative5 (because the parent id is 7 whose parent id is 5 whose parent id is 3)
I'm using SQL Server 2008. Hope that makes sense, any help is appreciated.
Try this
;WITH CTE
AS
(
SELECT [id], [name] FROM Parents WHERE [name] = 'parent3'
UNION ALL
SELECT T1.[id], T1.[name] FROM CTE c
INNER JOIN Parents T1 ON c.[id] = T1.[parent_id]
)
SELECT * FROM Relatives
WHERE [parent_id] IN (SELECT [id] FROM CTE)
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.