按一个参数选择值,用其他参数完成表

时间:2015-05-14 20:09:41

标签: mysql sql

很难在标题中解释我的问题。 基本上我有一个包含多种语言的翻译表,看起来像这样

+---------------+----------------------------------+----------+
| name          | translation                      | language |
+---------------+----------------------------------+----------+
| translation_1 | This is text for translation n.1 | en       |
+---------------+----------------------------------+----------+
| translation_2 | This is text for translation n.2 | en       |
+---------------+----------------------------------+----------+
| translation_3 | This is text for translation n.2 | en       |
+---------------+----------------------------------+----------+
| translation_2 | Toto je text pre preklad č.2     | sk       |
+---------------+----------------------------------+----------+

现在我需要使用语言'sk'来获取翻译,但我不能确定所有语言都会有所有翻译,所以我想要实现的是使用语言'sk'获取所有内容并完成翻译language'en'(这将是默认语言,并且将始终具有所有翻译)。

这应该是结果

+---------------+----------------------------------+----------+
| name          | translation                      | language |
+---------------+----------------------------------+----------+
| translation_1 | This is text for translation n.1 | en       |
+---------------+----------------------------------+----------+
| translation_2 | Toto je text pre preklad č.2     | sk       |
+---------------+----------------------------------+----------+
| translation_3 | This is text for translation n.2 | en       |
+---------------+----------------------------------+----------+

感谢您的建议!

2 个答案:

答案 0 :(得分:3)

考虑到“en”的每个翻译都存在,您可以

SELECT
  en.name,
  IFNULL(sk.translation, en.translation) AS translation,
  IFNULL(sk.language, en.language) AS language
FROM translation AS en
  LEFT JOIN translation AS sk ON en.name = sk.name AND sk.language = "sk"
WHERE en.language = "en"

您选择所有英语翻译并使用瑞典语翻译进行左连接。对于翻译和语言列,您声明更喜欢瑞典语,但英语

答案 1 :(得分:0)

您可以使用变量来模拟其他RDBMS中可用的ROW_NUMBER()窗口函数:

SELECT name, translation, language
FROM (
  SELECT translation, language,
         @row_number:= CASE WHEN @name = name THEN @row_number+1
                            ELSE 1
                       END AS row_number,
         @name:=name AS name              
  FROM translations
  ORDER BY name, CASE WHEN language = 'sk' THEN 1
                      WHEN language = 'en' THEN 2
                      ELSE 3
                 END ) t
WHERE row_number = 1                 
ORDER BY name
每次遇到新的@row_number时,

name都会被重置。在每个name分区中,值@row_number = 1指向sk转换(如果可用),否则指向en转换。

SQL Fiddle Demo