oracle 表连接查询思想:
在连接多表查询中,各表通过某字段关联,当我们分别要查这几个表的某个字段时,
有两种思路。
1.先通过两表的连接,查到之后完成查询要用到的字段,形成中间表 再把中间表和下一个表连接起来查询需要的字段,形成新的中间表再和下一个表连接,依次类推,直到查到所需要的所有字段(即,多层嵌套查询)。
2.开始时,直接把所有的表连接起来,直接提取各表中需要的字段。
下面给出实例:
现有表 cs_user_organnode,cs_organ_model,cs_organ_node三张表
cs_organ_node如下图需要的字段,
cs_organ_model如下图需要的字段,其中,org_node_id和parent_node_id(org_node_id上一级的id)是该表的外键,两字段都关联cs_organ_node中的id
cs_user_organnode 如下图需要字段,其中字段organ_node_id关联表cs_organ_node中的id
现在需求:
1需要三个字段的值:name,security_user_id,code。
2,其中name的值为organ_node_id对应上一级的值。
3,条件:cs_organ_node中的removed值为0。
例如:
最后查询出来的结果(其中game等于name值,twid等于security_user_id,thiscode等于code值):
运用第一种查询方案:
select no2.name as gname, twm1.no1id as twid, twm1.thiscode
from (select un1.security_user_id as no1id,
onde2.no2parcode as parentcode,
onde2.no2code as thiscode
from (select nm1.no1code as no2code,
no3.code as no2parcode,
nm1.n1id as no3id
from (cs_organ_model cs_mo1
left join cs_organ_node no3
on no3.id = nm1.mo1parid
where no3.removed = 0) onde2
left join cs_user_organnode un1
on un1.organ_node_id = onde2.no3id) twm1
left join (select * from cs_organ_node onode where onode.removed = 0) no2
on no2.code = twm1.parentcode
运用第二种查询方案:
select from(select code,id from cs_organ_node where remove = 0) A
inner join cs_organ_model B on a.id=b.org_node_id
inner join cs_user_organnode C on c.organ_node_id=a.id
inner join cs_organ_node D on d.id=b..parent_node_id
当然此实例还可以用级联查询,更加简单。本文章主要讲连接查询,此查询方案不做细讲。