余数据库I具有的每个标识信息的2个以下。控制他们的公司,以及他们有一点控制权的公司。SQL多条件CTE递归
沿东西线,2台(忽略了一些独特的标识符):
组织
orgid | org_immediate_parent_orgid
1 | 2
2 | 2
3 | 1
5 | 4
的关系ORGID - > org_immediate_parent_orgid意味着公司拥有母公司。 POR我及其相关仅org_immediate_parent_orgid - > ORGID公司的母公司拥有作为辅助
org_affiliations
orgid | affiliated_orgid
2 | 3
2 | 5
4 | 1
1 | 5
ORGID - > affiliated_orgid是公司拥有子公司
的可视化表示应例如:
在从组织红色的关系,蓝色的关系org_affiliations。
如果想要得到2(2或子公司的儿子)拥有的所有公司中有他们的一些部分:
select m.org_immediate_parent_orgid
,m.orgid
from oa.organizations m
where m.org_immediate_parent_orgid is not null
start with m.orgid in (Identifiers)
connect by nocycle prior m.orgid=m.org_immediate_parent_orgid
回报
org_immediate_parent_orgid| orgid
1 | 2
2 | 2
3 | 1
如果想要获得所有的公司分别为2 (或2下属子)中有他们一些部分:
select aff.orgid,aff.affiliated_orgid
from oa.org_affiliations aff
where aff.affiliated_orgid is not null
start with aff.orgid in(Identifiers)
connect by nocycle prior aff.affiliated_orgid =aff.orgid
回报
orgid | affiliated_orgid
2 | 3
2 | 5
因此,所有可能的关系:
- AFF - > AFF
- AFF - >子
- 子 - > AFF
- 子 - >子
我只能找到子 - >子(子公司子公司),关系(2 - > 1和关系1 - > 3)和AFF - > AFF,关系(2 - >图3和关系2 - > 5)。另外它需要我2个单独的查询。
我怎么能拉一个单一的递归查询所有可能的关系?
如果我通过标识2应该尽可能以下返回:
Relation | Loop| orgid | children
Sub | 1 | 2 |2
Sub | 1 | 2 |1
Aff | 1 | 2 |3
Aff | 1 | 2 |5
Sub | 2 | 1 |3
Aff | 2 | 1 |5
在每个循环中会检查潜艇和附属公司的每个标识符。重复为新的孩子。
对如何处理它的主意?
TL:DR: 2表(子公司\附属公司),2查询。希望从一家公司的单个查询中找到所有子公司和附属公司以及所有可能的子\ affs组合。最终预期结果显示,只需按照图片表示即可。
编辑:由Craig评论,我修正了输出。
编辑2:以下的好帮手克雷格和鲍勃贾维斯给我继续遇到问题。
收集子公司,下面的代码工作flawlessy,输出是因为我想:
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
同为AFF:
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
,但不能有 “UNION ALL”?
with
relations 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
)
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
在SQL开发人员,我就去检查“从7每一跳到400K解释计划和成本,只需通过添加‘UNION ALL’。任何workarround?是CTE内部的问题,在UNION ALL?
在那里我有COMP-分次AFF,或者发现公司的所有子公司或附属机构为
+1剪切美。然而,太长...没有听:) – Bohemian
不得不解释:D – blueomega
它太长,我阅读,理解和回复! – Kangkan