0

如何使用左外连接连接 3 个表?我能够在 table1 和 table2 之间进行左外连接,但不能在 table3 之间进行。

我尝试了以下方法,但不知道如何加入 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_codenull
  • table1.id可能没有任何匹配项table3.id

我想在 table1 中找到具有table1.job_title = 'accounting'或在 table3 中具有table3.job_history = 'accounting'when的记录,table1.id = table3.id并通过以下方式获取 table2 状态table1.status_code = table2.status_code

4

3 回答 3

0

由于您在所有表上都没有相同的字段,为了匹配您的条件,您可能会找到更简单的方法来运行连接,例如:

 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'
于 2013-03-24T20:42:22.103 回答
0

该SQL假设表1、表2和表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 中的每条记录,表 3 中可能会有多个记录。如果是这种情况,您将需要执行子查询来查找所有目前或以前拥有会计职称的人,即

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')
于 2013-03-24T20:46:10.253 回答
0

我怀疑您想加入table2ontable1status_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'
于 2013-03-24T20:47:03.033 回答