CTE,在2个不同的表中进行递归搜索

时间:2011-08-09 07:00:04

标签: sql oracle recursion common-table-expression

我有2个查询从不同的表中收集数据,这些表都是递归的,但是密切相关。

两者都运作良好:

首先拉动子公司:

with
relations as
(
select orgid as children,org_immediate_parent_orgid as orgid,'Sub' as relation
from oa.organizations 
)
select distinct relation, level, orgid, children
from relations
where children is not null
start with orgid in (identifier)
connect by
nocycle prior children = orgid
order by 2,3,4

第二个附属公司:

with
relations as
(
select affiliated_orgid as children, orgid as orgid,'Aff' as relation
from oa.org_affiliations    
)
select distinct relation, level, orgid, children
from relations
where children is not null
start with orgid in (identifier)
connect by
nocycle prior children = orgid
order by 2,3,4
正如我所预料的那样,

递归顺利进行。是的,孩子和orgid在查询中交换,我会说子公司是从属关系的“反向关系”(至少在概念上),但结果是预期的

我想一起跑。现在我想要第一个循环的结果(对于subs和aff)作为以下循环中的输入(对于subs和aff),直到children为null。因此,如果我从每个结果中得到一个结果,我想要两个id作为每个查询的输入。

我知道我不能在“With As”里面做以下事情。

select orgid as children,org_immediate_parent_orgid as orgid,'Sub' as relation
from oa.organizations

UNION ALL

select affiliated_orgid as children, orgid as orgid,'Aff' as relation
from oa.org_affiliations    

我的替代方案是什么?解决方案?

0 个答案:

没有答案