SQL parent child recursive query - Includes Relatives relatives

情到浓时终转凉″ 提交于 2019-12-11 08:46:16

问题


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;


来源:https://stackoverflow.com/questions/30538873/sql-parent-child-recursive-query-includes-relatives-relatives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!