我有两列的下表。
Parent Child
A C
A D
B A
B E
C H
J C
F G
G I
所以我需要传递A的父母,我应该得到以下回复 - 所有的父母和孩子,但也是所有的父母和孩子与A(父母或孩子)相关的人我需要所有的父母和孩子等等。
所以在传递给proc的A的例子中我会得到以下
A C
A D
B A
B E
C H
J C
如果F被通过,我会得到
F G
G I
答案 0 :(得分:1)
select * from test
where parent in (
select parent from test
where parent = 'F' or child = 'F'
union
select child from test
where child = 'F' or parent = 'F')
or child in (
select parent from test
where parent = 'F' or child = 'F'
union
select child from test
where child = 'F' or parent = 'F');
答案 1 :(得分:1)
试试这个,它类似于评论中给出的链接,但同时考虑了父和子递归。希望它对你有用。
WITH relationships AS (
SELECT *
FROM Table
WHERE Child = 'A'
UNION ALL
SELECT p.*
FROM Table p
JOIN relationships pa on pa.Child = p.Parent
UNION ALL
SELECT c.*
FROM Table c
JOIN relationships ch on ch.Parent = c.Child
)
select *
from name_tree;