我相信这个版本对于大表应该更有效,因为它只需要通过 Table1 而不是 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 Fiddle 链接,将上述内容与多表连接选项进行比较:http ://sqlfiddle.com/#!3/1f5e6/1