我相信這個版本應該是大表更有效,因爲只需要一通過表1而不是3:
離開這裏的答案它應該是學術興趣,但它的性能比多個連接選項差,所以請不要使用此:
if OBJECT_ID('Table2') is not null drop table Table2
if OBJECT_ID('Table1') is not null drop table Table1
create table Table1
(
Reason_Id bigint not null identity(1,1) primary key clustered
, Reason_Description nvarchar(256)
)
create table Table2
(
Id bigint not null identity(1,1) primary key clustered
, Reason1_Id bigint foreign key references Table1(Reason_Id)
, Reason2_Id bigint foreign key references Table1(Reason_Id)
, Reason3_Id bigint foreign key references Table1(Reason_Id)
)
insert Table1 select 'Desc 1'
insert Table1 select 'Desc 2'
insert Table1 select 'Desc 3'
insert Table1 select 'Desc 4'
insert Table2 select 1, 2, 3
insert Table2 select 4, 4, 4
select a.id
, max(case when a.Reason1_Id = b.Reason_Id then b.Reason_Description end)
, max(case when a.Reason2_Id = b.Reason_Id then b.Reason_Description end)
, max(case when a.Reason3_Id = b.Reason_Id then b.Reason_Description end)
from Table2 a
left outer join Table1 b --could do an inner join but left outer is safer
on b.Reason_Id in (a.Reason1_Id, a.Reason2_Id, a.Reason3_Id)
group by a.Id
這裏有一個SQL小提琴鏈接上面的對比對多表連接選項:http://sqlfiddle.com/#!3/1f5e6/1
您使用的RDBMS是什麼? – Taryn
看看http://sqlfiddle.com/#!3/3b9d1/2 –