0

我有一个名为“测试”的表。它包含父列和子列。

Parent  Child
  1      101
  1      102
  1      103
 101     121
 101     123
 103     133
 121     80
 121     81

现在,我写了一个查询,它为给定的“1”值带来了所有的孩子/父母。

( SELECT parent,child,LEVEL FROM TEST
    START WITH child= 1
    CONNECT BY PRIOR parent=child) 
UNION ALL
   (SELECT parent,child,LEVEL FROM TEST
      START WITH parent=1
      CONNECT BY PRIOR child=parent)
      ORDER BY parent

但是我想要该层次结构中的所有子/父,而不管给定的任何值..即如果我给“80”....,我必须获取最高父值(在本例中为“1”),然后搜索所有下面那个最高父值的子级。

4

1 回答 1

3

您可以使用递归查询和伪列CONNECT_BY_ISLEAF来查找节点的最终祖先:

SELECT parent AS ancestor 
  FROM X 
  WHERE CONNECT_BY_ISLEAF <> 0
  START WITH child=80 
  CONNECT BY PRIOR parent=child
--           ^^^^^^^^^^^^^^^^^^
--             ascendant order

一旦你有了“终极祖先”,第二个递归查询将从该节点获取所有后代:

SELECT child AS descendant, LEVEL
  FROM X
  START WITH parent=1 
  CONNECT BY PRIOR child=parent
--           ^^^^^^^^^^^^^^^^^^
--            descendant order

请注意LEVEL允许您知道节点与其最终祖先之间的“距离”的伪列。

把它们放在一起:

SELECT child AS descendant, LEVEL
  FROM X
  START WITH parent IN (

    SELECT parent AS ancestor
      FROM X 
      WHERE CONNECT_BY_ISLEAF <> 0
      START WITH child=80 
      CONNECT BY PRIOR parent=child

  ) 
  CONNECT BY PRIOR child=parent

生产,给定您的样本数据:

DESCENDANT  LEVEL
101         1
121         2
80          3
81          3
123         2
102         1
103         1
133         2
于 2014-10-04T13:44:07.767 回答