日期:2014-05-17  浏览次数:20659 次

请教SQL~~
请教SQL

表结构如:
Parent Child
 A B
 A D
 A F
 B T
 B S
 D H
 F M
 N B
 N L
 N Z
 L D
 L C
 Z D
 Z F

如何写SQL语句分别得到任何一个parent下的存在的亲子关系。
例如:
A下面存在的亲子关系有:
A - B
A - D
A - F
B - T
B - S
D - H
F - M


如何写SQL语句得到任何一个parent下的所有节点,直至根节点
例如:
A的子孙有:
B\T\S\D\H\F\M

如何写SQL语句得到任何一个child的所有祖先.
例如:
D的祖先有:
L/N/Z/A

谢谢~~~

------解决方案--------------------
--根据子查父集
select * from tablename
start with child = 'F'
connect by prior child = parent
------解决方案--------------------
D的长辈们
SQL code

with t as
( select 'A' parent,'B' child from dual UNION  
  select 'A' parent,'D' child from dual UNION
  select 'A' parent,'F' child from dual UNION
  select 'B' parent,'T' child from dual UNION
  select 'B' parent,'S' child from dual UNION
  select 'D' parent,'H' child from dual UNION
  select 'F' parent,'M' child from dual UNION
  select 'N' parent,'B' child from dual UNION
  select 'N' parent,'L' child from dual UNION
  select 'N' parent,'Z' child from dual UNION
  select 'L' parent,'D' child from dual UNION
  select 'L' parent,'C' child from dual UNION
  select 'Z' parent,'D' child from dual UNION
  select 'Z' parent,'F' child from dual 
 )
select distinct parent from t
 start with child='D'
connect by child = prior parent;