2013-03-24 111 views
0

如何连接3个左外连接的表?我能够做table1和table2之间的左外连接,但不能table3。ORACLE SQL:无法左连接3个表

我尝试了以下,但不知道如何加入table3。

select tab1.id, tab2.status, tab3.job_history 
from table1 tab1 
left outer join table2 tab2 on tab1.id=tab2.id 
where tab1.job_title='accounting' 

我的表架构是:

table 1: 
    id   number(5) primary key, 
    status_code number(5), 
    job_title varchar2(20) 
    name   varchar2(30) 


table 2: 
    status_code number(5) primary key, 
    status  varchar2(15) 

table 3: 
    id   number(5) 
    job_history varchar2(20) 

条件:

  • table1.status_code可以null
  • table1.id可能没有任何匹配table3.id

我想找到一个具有table1.job_title = 'accounting' table1中的记录或表3中具有table3.job_history = 'accounting'table1.id = table3.id并同时获得与table1.status_code = table2.status_code

+0

您显示的模式没有'table 2 id',那么你想要执行什么'left outer join'? (你的SQL在tab1.id = tab2.id中显示'table2 tab2',但没有table2 ID列。) – 2013-03-24 20:44:17

+0

表1和表3之间的关系是一对多关系吗? – mickfold 2013-03-24 20:56:08

回答

0

的表2地位,因为你对所有表不相同的字段,要,你可能符合您的条件会发现运行加入喜欢更简单的方法:

select 
     tab1.id, 
     tab2.status, 
     tab3.job_history 
    from 
     table1 tab1,  
     table2 tab2, 
     table3 tab3 
    where 
     tab1.job_title='accounting' 
     --ADD ADITIONAL FILTERING HERE 

查询在第3个表的连接是这个样子:

select 
    tab1.id, 
    tab2.status, 
    tab3.job_history 
from 
    table1 tab1 
left outer join 
    table2 tab2 on tab1.id=tab2.id 
left outer join 
    table3 tab3 on tab3.id = tab1.id 
where 
    tab1.job_title='accounting' 
+0

这不起作用。你错过了'table2'中没有'ID'列的事实。 – 2013-03-24 20:49:18

+0

@KenWhite - 谢谢,是的,我更新了答案。 – evgenyl 2013-03-24 20:51:12

0

这个SQL假设有3

select tab1.id, tab2.status, tab3.job_history 
from table1 tab1 
left outer join table2 tab2 on tab2.status_code = tab1.status_code 
left outer join table3 tab3 on tab3.id = tab1.id 
where tab1.job_title = 'accounting' or tab3.job_history = 'accounting' 

表3看起来它含有某种形式的历史记录的表1,表2和表之间有一个一对一的关系,所以它很可能有将超过表3中的一个记录对表1.每个记录。如果是这样,你将需要执行一个子查询发现,在目前或以前有会计的职务所有的人的情况下,即

select tab1.id, tab2.status, tab1.job_title 
from table1 tab1 
left outer join table2 tab2 on tab2.status_code = tab1.status_code 
where tab1.job_title = 'accounting' or 
     tab1.id in (select id from tab3 where job_history = 'accounting') 
+1

这不起作用。你错过了'table2'中没有'ID'列的事实。 – 2013-03-24 20:48:33

+0

好点!我会更新我的答案。 – mickfold 2013-03-24 20:51:32

0

我怀疑你想加入table2table1status_code而不是id,因为有 ID栏位table2。要加入第三张表格,只需添加另一个LEFT OUTER JOIN(或任何其他JOIN)。

select 
    tab1.id, 
    tab2.status, 
    tab3.job_history 
from 
    table1 tab1 
left outer join 
    table2 tab2 on tab2.status_code = tab1.status_code 
left outer join 
    table3 tab3 on tab3.id = tab1.id 
where 
    tab1.job_title='accounting' or tab3.job_history = 'accounting'