如果一条记录不存在 select 另一条
If one record does not exist select another
我构建了一个多语言应用程序。数据库看起来像:
Table 东西
|id| img |url|
--------------
|1 | | |
|2 | | |
|3 | | |
Table things_translations
|id| thing_id | title | locale |
---------------------------------
|1 | 1 | | en |
|2 | 2 | | en |
|3 | 3 | | en |
|4 | 2 | | ru |
我的默认语言是英语 (locale=en)。
当我从 things_translations
获得翻译 title
的非英语语言,而该语言在数据库中尚不存在时,我想获取它的英文版本。
我尝试了以下查询,但 returns 所有记录:
select things.id
FROM things
INNER JOIN things_translations ON things.id = things_translations.thing_id
WHERE CASE WHEN things_translations.locale = ru IS NULL
THEN things_translations.locale = en END
通过上面的查询,我得到了 thing_id:2
的两种语言,但我只想得到 ru locale
而不是 en
因为存在。
我认为您的 CASE
评估为真,因此显示了所有内容。
您可以在各自的条款中加入 things_translations 两次——一次使用您选择的语言,一次使用英语。那么您的专栏将是 COALESCE(things_translations.title, things_translations_en.title)
。换句话说,尝试 things_translations(您的 selected-language 加入)作为标题,如果它为空,则使用 things_translations_en 中的标题。您还需要在 where 子句中使两个连接的 ID 相等,否则您会得到太多行。
我正在处理相同类型的应用程序并使用 CASE 解决了我的问题:
SELECT t.id FROM things t
INNER JOIN things_translations tt ON t.id = tt.thing_id
AND tt.locale = CASE WHEN
EXISTS(SELECT tte.locale FROM things_translations tte WHERE tt.thing_id = t.id AND tte.locale = 'ru') THEN 'ru'
ELSE 'en'
END
SELECT IFNULL(TT1.title,TT.title)
FROM things T
LEFT JOIN things_translations TT
ON (T.id = TT.thing_id AND TT.locale = 'en')
LEFT JOIN things_translations TT1
ON (T.id = TT1.thing_id AND TT1.locale = 'ru')
WHERE T.id = 2;
我构建了一个多语言应用程序。数据库看起来像:
Table 东西
|id| img |url|
--------------
|1 | | |
|2 | | |
|3 | | |
Table things_translations
|id| thing_id | title | locale |
---------------------------------
|1 | 1 | | en |
|2 | 2 | | en |
|3 | 3 | | en |
|4 | 2 | | ru |
我的默认语言是英语 (locale=en)。
当我从 things_translations
获得翻译 title
的非英语语言,而该语言在数据库中尚不存在时,我想获取它的英文版本。
我尝试了以下查询,但 returns 所有记录:
select things.id
FROM things
INNER JOIN things_translations ON things.id = things_translations.thing_id
WHERE CASE WHEN things_translations.locale = ru IS NULL
THEN things_translations.locale = en END
通过上面的查询,我得到了 thing_id:2
的两种语言,但我只想得到 ru locale
而不是 en
因为存在。
我认为您的 CASE
评估为真,因此显示了所有内容。
您可以在各自的条款中加入 things_translations 两次——一次使用您选择的语言,一次使用英语。那么您的专栏将是 COALESCE(things_translations.title, things_translations_en.title)
。换句话说,尝试 things_translations(您的 selected-language 加入)作为标题,如果它为空,则使用 things_translations_en 中的标题。您还需要在 where 子句中使两个连接的 ID 相等,否则您会得到太多行。
我正在处理相同类型的应用程序并使用 CASE 解决了我的问题:
SELECT t.id FROM things t
INNER JOIN things_translations tt ON t.id = tt.thing_id
AND tt.locale = CASE WHEN
EXISTS(SELECT tte.locale FROM things_translations tte WHERE tt.thing_id = t.id AND tte.locale = 'ru') THEN 'ru'
ELSE 'en'
END
SELECT IFNULL(TT1.title,TT.title)
FROM things T
LEFT JOIN things_translations TT
ON (T.id = TT.thing_id AND TT.locale = 'en')
LEFT JOIN things_translations TT1
ON (T.id = TT1.thing_id AND TT1.locale = 'ru')
WHERE T.id = 2;