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_codeすることができますnull
  • table1.idに一致するものがない可能性がありますtable3.id

table1 にあるレコードtable1.job_title = 'accounting'または table3 にtable3.job_history = 'accounting'あるレコードを検索し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 の間に 1 対 1 の関係があることを前提としています。

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

にはID 列がないため、ではなく に参加table2したいと考えています。3 番目のテーブルに参加するには、別の(または他の) を追加するだけです。table1status_codeidtable2LEFT OUTER JOINJOIN

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 に答える