假设我有这张表
translationId ItemId Lang Content
0 0 FR Livre
1 0 DE Buch
2 0 EN Book
3 0 NL Boek
4 1 FR Stylo
5 1 EN Pen
6 2 FR Plaque
7 2 NL Plaat
8 2 EN Plate
我想做一个select语句,它给出了以下结果
ItemId Lang Content
0 FR Livre
0 DE Buch
0 EN Book
0 NL Boek
1 FR Stylo
1 EN Pen
1 DE Pen /*it defaulted to EN*/
1 NL Pen /*it defaulted to EN*/
2 DE Plate /*it defaulted to EN*/
2 EN Plate
2 FR Plaque
2 NL Plaat
结果中发生的事情是,如果没有针对特定语言内容的Entery默认为英语,则始终可以使用英语。 这样做的最佳方式是什么?
答案 0 :(得分:2)
您可以创建一个子查询,其中包含每个Lang='EN'
记录的itemId和Content,在不同的语言列表中交叉连接,以获取所有潜在替换记录的列表。
从那里,您可以结合RIGHT OUTER JOIN
和COALESCE
来确定每个itemId
缺少的语言记录,并替换它们。
-- Create our temp table for testing, 'cause I'm too lazy to fiddle
SELECT 0 as translationId, 0 as ItemId, 'FR' as Lang, 'Livre' as Content
INTO #Test
UNION SELECT 1, 0, 'DE', 'Buch'
UNION SELECT 2, 0, 'EN', 'Book'
UNION SELECT 3, 0, 'NL', 'Boek'
UNION SELECT 4, 1, 'FR', 'Stylo'
UNION SELECT 5, 1, 'EN', 'Pen'
UNION SELECT 6, 2, 'FR', 'Plaque'
UNION SELECT 7, 2, 'NL', 'Plaat'
UNION SELECT 8, 2, 'EN', 'Plate'
-- Query starts here, replace #Test with your table name
SELECT
COALESCE(T1.itemId, T2.itemId) AS itemId,
COALESCE(T1.Lang, T2.Lang) AS Lang,
COALESCE(T1.Content, T2.Content) AS Content
FROM #Test T1
RIGHT OUTER JOIN (
/*
Create a subquery that contains the Content and itemId records
for each Lang='EN' record; we'll RIGHT OUTER JOIN on this
*/
SELECT itemId, Languages.Lang, Content
FROM #Test
CROSS JOIN (
-- Get our distinct list of languages
SELECT DISTINCT Lang
FROM #Test
) Languages
WHERE #Test.Lang = 'EN'
) T2 ON T1.itemId = T2.itemId and T1.Lang = T2.Lang
ORDER BY COALESCE(T1.itemId, T2.itemId)
DROP TABLE #Test -- Clean up our temp table