2013-03-24 104 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'