我有两列在下表中。
Parent Child
A C
A D
B A
B E
C H
J C
F G
G I
所以,我需要在A的父通过,我应该得到以下背全一的家长和孩子,但也所有的家长和孩子关联到A(父母一方或子女)那些我需要他们所有的父母和孩子等。
因此,在A的例子传递给PROC我会得到以下
A C
A D
B A
B E
C H
J C
若F获得通过,我只想得到
F G
G I
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');
试试这个,它类似于在评论中给出的链接,但同时说明父母和孩子递归。 希望这会为你工作。
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;