SQL - 当translate不存在时,回退到默认语言

时间:2017-09-14 08:59:04

标签: sql sql-server internationalization

使用以下结构在表(tbl_i18n)中以不同语言记录文本:

text_FK | language_FK | value
-----------------------------
    1   |       1     | hello
    1   |       2     | hallo
    2   |       1     | world
    3   |       1     | test

通过简单的连接提供特定语言(id = 2)的文本:

SELECT [value] FROM tbl_i18n i
   JOIN tbl_products p ON p.text_id = i.text_FK
   JOIN tbl_languages l ON l.id = i.language_FK AND i.language FK = 2;

结果是:

 value
-------
 hallo

前面提到的select语句如何改变,所以我们可以使用默认语言,当文本字段的翻译不存在时,将显示其后备文本,结果将变为:

 value
-------
 hallo
 world
 test

2 个答案:

答案 0 :(得分:2)

LEFT JOIN语言表两次。第一次获得通缉语言,第二次获得后备价值。如果可用,请使用COALESCE选择想要的语言,否则使用后备语言。

SELECT coalesce(l1.[value], l2.[value])
FROM tbl_i18n i
JOIN tbl_products p ON p.text_id = i.text_FK
LEFT JOIN tbl_languages l1 ON l.id = i.language_FK AND i.language_FK = 2
LEFT JOIN tbl_languages l2 ON l.id = i.language_FK AND i.language_FK = 1;

答案 1 :(得分:0)

我认为在简单的英语中,您希望每个language_FK具有最高可用text_FK

WITH X AS (
SELECT *
     ,ROW_NUMBER() OVER (PARTITION BY text_FK ORDER BY language_FK DESC)rn
FROM TableName 
)
SELECT *
FROM X
WHERE X.rn = 1