3
Table1:

Child     Parent       a

Bob        Chris       2
Chris      Kate        1
Shane      Lana        3
Nala       Bob         4


Table2:

b           Talent      

1           'something'
2           'nothing'
3           'something'
4           'nothing'

SELECT  Child
FROM Table1
INNER JOIN Table2 ON (Table1.a =  Table2.b)
WHERE Table2.Talent = 'something'
connect by prior  Table1.Child =  Table1.Parent

此代码返回父母行

克里斯

如果未包含“Where”子句,则代码将返回:

Bob
Chris
Kate

Chris
Kate

Shane
Lana

etc

我要返回的是连续的以下内容,而不是列中的内容:

鲍勃·克里斯

其中 Chris 是有才能的人,并且是 Bob 的父母,因此代码不仅返回父母,还返回发起对该父母的查询的孩子,所以在这段代码中:

SELECT  Child
FROM Table1
INNER JOIN Table2 ON (Table1.a =  Table2.b)
WHERE Table2.Talent = 'something'
connect by prior  Table1.Child =  Table1.Parent

我会拥有具有天赋的孩子克里斯和发起搜索克里斯的前一个孩子鲍勃,所以假设 Bob 是 Gala 的孩子,而 Gala 是 Chris 的孩子,我仍然希望在结果中只得到 Bob 和 Chris .

条件:我无权创建临时表或任何类型的表,所以我不能使用任何循环来执行此操作,除非我不知道如何在没有临时表的情况下执行此操作

我不知道如何从“先前”语句和实际上是前一个孩子的父母的新“孩子”之前返回一个孩子。

4

2 回答 2

2

您只需要使用connect_by_root运算符。

我不确定查询目标(例如,如果父母没有才华,返回或不返回有才华的祖父)但该运算符的用法可能如下所示:

select 
  originated_from_child, 
  found_ancestor, 
  is_ancestor_talented
from (
  select 
    CONNECT_BY_ROOT relations.child  originated_from_child,
    relations.parent                 found_ancestor,
    ( 
      select count(1) 
      from table2 
      where 
        b = a 
        and 
        talent = 'something' 
        and 
        rownum = 1
    )                                is_ancestor_talented
  from 
    table1 relations
  start with 
    relations.a in (
      select talents.b 
      from table2 talents 
      where talents.talent = 'something')
  connect by 
    prior relations.child = relations.parent
)
where 
  originated_from_child <> found_ancestor
  and
  is_ancestor_talented = 1

SQLFiddle 示例

于 2013-08-26T17:13:41.860 回答
1

您可以使用“HR”数据库进行测试

SELECT last_name "Employee", CONNECT_BY_ROOT last_name "Manager",
   LEVEL-1 "Pathlen", SYS_CONNECT_BY_PATH(last_name, '/') "Path"
   FROM employees
   WHERE LEVEL > 1 and department_id = 110
   CONNECT BY PRIOR employee_id = manager_id;

Employee        Manager         Pathlen Path   
--------------- ------------ ---------- ----------------------------   
Higgins         Kochhar               1 /Kochhar/Higgins   
Gietz           Kochhar               2 /Kochhar/Higgins/Gietz   
Gietz           Higgins               1 /Higgins/Gietz   
Higgins         King                  2 /King/Kochhar/Higgins   
Gietz           King                  3 /King/Kochhar/Higgins/Gietz  
于 2013-12-06T03:36:29.210 回答