条件上的SQL查询
我正在编写一个查询来检索翻译后的内容。我希望这样,如果给定语言id没有翻译,它会自动返回id为1的默认语言的翻译条件上的SQL查询,sql,foreign-keys,Sql,Foreign Keys,我正在编写一个查询来检索翻译后的内容。我希望这样,如果给定语言id没有翻译,它会自动返回id为1的默认语言的翻译 select Translation.Title ,Translation.Summary from Translation where Translation.FkLanguageId = 3 -- If there is no LanguageId of 3, select the record with LanguageId of 1. 我在MS SQL中工作,
select Translation.Title
,Translation.Summary
from Translation
where Translation.FkLanguageId = 3
-- If there is no LanguageId of 3, select the record with LanguageId of 1.
我在MS SQL中工作,但我认为这个理论不是DBMS特有的
提前感谢。根据您对问题的措辞,假设每次翻译仅一行。如果每个FkLanguageId有多行,而我误解了,请告诉我们,查询当然会变得更复杂
select TOP 1
Translation.Title
,Translation.Summary
from
Translation
where
Translation.FkLanguageId IN (1, 3)
ORDER BY
FkLanguageId DESC
您可能会在另一个RDBMS中使用LIMIT,也许这是一个肮脏的解决方案,但它可以帮助您
if not exists(select t.Title ,t.Summary from Translation t where t.FkLanguageId = 3)
select t.Title ,t.Summary from Translation t where t.FkLanguageId = 1
else
select t.Title ,t.Summary from Translation t where t.FkLanguageId = 3
假设该表包含按
PhraseId
WITH Trans As
(
select Translation.Title
,Translation.Summary
,ROW_NUMBER() OVER (PARTITION BY PhraseId ORDER BY FkLanguageId DESC) RN
from Translation
where Translation.FkLanguageId IN (1,3)
)
SELECT *
FROM Trans WHERE RN=1
由于您对pastie.org的引用表明您正在表中查找短语或特定菜单项名称,因此我假设有一个短语ID来标识所涉及的短语
SELECT ISNULL(forn_lang.Title, default_lang.Title) Title,
ISNULL(forn_lang.Summary, default_lang.Summary) Summary
FROM Translation default_lang
LEFT OUTER JOIN Translation forn_lang ON default_lang.PhraseID = forn_lang.PhraseID AND forn_lang.FkLanguageId = 3
WHERE default_lang.FkLanguageId = 1
这假设存在一个TranslationKey,它将一个“主题”与多个不同的翻译语言相关联:
SELECT
isnull(tX.Title, t1.Title) Title
,isnull(tX.Summary, t1.Summary) Summary
from Translation t1
left outer join Translation tX
on tx.TranslationKey = t1.Translationkey
and tx.FkLanguageId = @TargetLanguageId
where t1.FkLanguageId = 1 -- "Default
我在MS SQL中工作,但不认为这有多大区别,因为这只是我想要帮助的逻辑,“相同”的翻译是如何分组的?当然,这个表是短语的集合,所以必须有短语ID或类似的东西。表结构是什么样子的?回答很好,请您解释一下如何将其集成到更复杂的查询中,例如:@Greg:请参阅Martin的答案,该答案允许每个ID有多行。您需要将“=3”条件移动到连接中:这是一个内部连接,因为它是正确的!我没有正确地想清楚。