如何使用左外连接加入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_code
可以是null
table1.id
可能与table3.id
我希望在table1.job_title = 'accounting'
找到包含table3.job_history = 'accounting'
或表3中的{1}}的table1中的记录,并使用table1.id = table3.id
获取table2状态
答案 0 :(得分: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'
答案 1 :(得分: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中的每条记录可能会有多条记录。如果是这种情况,则需要执行一个子记录。查询以查找当前或以前拥有会计职称的所有人,即
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')
答案 2 :(得分:0)
我怀疑您想要table2
加table1
status_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'