[英]Smartest way to join two SQL tables on a lookup value
I have two tables in Sql Server 2008 我在Sql Server 2008中有两个表
Items
------
ItemNo
StartDate
Translation
-------
ItemNo
StartDate
Language
Description
In the Translations table there are multiple translations for each product, ie. 在“翻译”表中,每个产品都有多个翻译,即。
ItemNo: 123
StartDate: 2011-11-02
Language: SE
Description: 'Bla1'
ItemNo: 123
StartDate: 2011-11-02
Language: DK
Description: 'Bla2'
How can I build a fast select statement that outputs a single line for each product without using too many lookups, like 如何构建快速选择语句,以在不使用过多查找的情况下为每个产品输出一行
Itemno StartDate DK SE
------------------------------------
123 2011-11-02 Bla1 Bla2
Thanx in advance Jens 提前感谢詹斯
Here is a version using XML to do what you want. 这是使用XML来完成您想要的事情的版本。 I have not tested the performance against the other methods suggested in the comment sections.
我尚未针对注释部分中建议的其他方法测试性能。
Can't see why StartDate
should be in both tables other than that it is part of the PK in Items
table. 除了
StartDate
是Items
表中PK的一部分之外,看不到为什么它应该在两个表中都存在。 If StartDate
is not part of the PK you can safely remove it from all joins. 如果
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.