MySQL - 检索具有特定字段条件但具有回退字段条件的行

时间:2011-05-06 05:30:41

标签: mysql

假设我们有这3个表,

语言

language_id     name
1               English
2               Tagalog

颜色

color_id
1
2
3
4

颜色翻译

color_translations_id   color_id    language_id   name
1                       1           1             Black
2                       2           1             White
3                       3           1             Red
4                       4           1             Blue
5                       1           2             Itim
6                       2           2             Puti

假设我想获得Tagalog中每种颜色的所有颜色转换行,但是使用英语的后备语言。结果应该是

color_translations_id   color_id    language_id   name
5                       1           2             Itim
6                       2           2             Puti
3                       3           1             Red
4                       4           1             Blue

此外,如果翻译表是这样的

color_translations_id   color_id    language_id   name
1                       1           1             Black
2                       2           1             White
3                       3           1             Red
4                       4           1             Blue

即使没有Tagalog行,我也应该返回所有4行,因为我的后备语言是英文

有没有办法在SQL中执行此操作?

1 个答案:

答案 0 :(得分:0)

这是为SQL Server编写的,我不得不稍微更改名称,但我的想法是在那里,我没有使用任何专有功能,所以它应该工作。您可能需要将INNER JOIN更改为JOIN。

WITH PrimaryLanguageColors AS 
  (SELECT color_id, color_translations_id
   FROM ColorTranslations INNER JOIN Languages
   ON ColorTranslations.language_id = Languages.language_id 
   WHERE Languages.Name = 'Tagalog')
SELECT color_translations_id, color_id, ColorTranslations.language_id,
  ColorTranslations.name 
FROM ColorTranslations INNER JOIN Languages 
ON ColorTranslations.language_id = Languages.language_id
WHERE color_translations_id IN (SELECT color_translations_id 
                                FROM PrimaryLanguageColors)
OR (color_id NOT IN (SELECT color_id FROM PrimaryLanguageColors)
    AND Languages.Name = 'English')