SQL parent child recursive query - Includes Relati

2019-08-04 10:14发布

问题:

I have the following Table with two columns.

Parent  Child
A       C
A       D
B       A
B       E
C       H
J       C
F       G
G       I

So I need to pass in a Parent of A and I am supposed to get the following back- All of a's Parent's and children but Also all of the Parents and Children to those associated to A (either parent or children) I need all their parents and children and so on.

SO in the example of A being passed to the proc I would get the following

A   C
A   D
B   A
B   E
C   H
J   C

If F was Passed I would just get

F   G
G   I

回答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');


回答2:

Try this, it is similar to the link given in the comments but accounts for both parent and child recursion. Hopefully it will work for you.

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;