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
此代码返回父行
Chris
如果不包含“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
我会有具有天赋的孩子克里斯和发起寻找克里斯的前一个孩子鲍勃,所以假设如果鲍勃是加拉的孩子,而加拉是克里斯的孩子,我仍然只想在结果中得到鲍勃和克里斯。
条件:我没有创建临时表或任何类型的表的权限,因此我无法使用任何循环来执行此操作除非我只是不知道如何在没有临时表的情况下做到这一点
我不知道如何从“先前”语句之前返回一个孩子,而新的“孩子”实际上是前一个孩子的父母。
您所需要的只是使用connect_by_root http://docs.oracle.com/cd/B19306_01/server.102/b14200/operators004.htm#i1035022操作员。
我不确定查询目标(例如,如果父母没有才华,则返回或不返回有才华的祖父),但该运算符的用法可能如下所示:
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 示例 http://www.sqlfiddle.com/#!4/c409c/8
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)