在查找值上连接两个SQL表的最智能方法

我在Sql Server 2008中有两个表

Items
------
ItemNo
StartDate


Translation
-------
ItemNo
StartDate
Language
Description

在翻译表中,每个产品都有多个翻译,即.

ItemNo: 123
StartDate: 2011-11-02
Language: SE
Description: 'Bla1'
ItemNo: 123
StartDate: 2011-11-02
Language: DK
Description: 'Bla2'

如何构建一个快速选择语句,为每个产品输出一行而不使用太多查找,例如

    Itemno  StartDate  DK     SE
------------------------------------
    123     2011-11-02 Bla1   Bla2

Thanx提前

最佳答案 这是一个使用XML来完成你想要的版本.我没有根据评论部分中建议的其他方法测试性能.

无法理解为什么StartDate应该在两个表中,而不是它是Items表中PK的一部分.如果StartDate不是PK的一部分,您可以安全地从所有连接中删除它.

declare @Items table
(
  ItemNo int,
  StartDate date
)

declare @Translation table
(
  ItemNo int,
  StartDate date,
  Language varchar(2),
  Description varchar(20)
)

insert into @Items values
(123, '2011-11-02')

insert into @Translation values
(123, '2011-11-02', 'DK', 'Bla1'),
(123, '2011-11-02', 'SE', 'Bla2')


select I.ItemNo,
       I.StartDate,
       T.Trans.value('(Trans[@Language="DK"]/Desc)[1]', 'varchar(20)') as DK,
       T.Trans.value('(Trans[@Language="SE"]/Desc)[1]', 'varchar(20)') as SE
from @Items as I
  inner join (select T1.ItemNo,
                     T1.StartDate,
                     (select T2.Language as '@Language',
                             T2.Description as 'Desc'
                      from @Translation as T2
                      where T1.ItemNo = T2.ItemNo and
                            T1.StartDate = T2.StartDate
                      for xml path('Trans'), type) as Trans
              from @Translation as T1
              group by T1.ItemNo,
                       T1.StartDate) as T
    on I.ItemNo = T.ItemNo and
       I.StartDate = T.StartDate                       
点赞