简体   繁体   English

SQL查询(CASE)中的流控制/条件

[英]flow control/condition in SQL query (CASE)

I have a CMS that is multi-lingual. 我有一个多语言的CMS。 There are about 300 words and phrases used throughout the system that change when the user changes the selected language. 整个系统中大约有300个单词和短语会在用户更改所选语言时更改。 English is the default language. 英语是默认语言。 Other languages may not, at any given point, have been completely translated. 在任何给定的点上,其他语言可能都没有被完全翻译。 I want the English version to be the fall back on a case by case basis where a particular word or phrase has not been translated into the selected language. 我希望英语版本可以根据具体情况而退回,因为特定单词或短语尚未翻译成所选语言。 (stack overflow doesn't allow the table html tag, so I will show two records using an unordered list) (堆栈溢出不允许使用表格html标签,因此我将使用无序列表显示两条记录)

language_id label         translation
en          your_account  Your Account
zh          your_account  您的賬戶

Primary key is on language_id and label 主键位于language_id和label上

I am using PDO on MariaDB. 我在MariaDB上使用PDO。 The part of my query that I am stuck on is the if/case statement, which I know is completely wrong below, but it demonstrates what I wish to accomplish : 我遇到的查询部分是if / case语句,下面我知道这是完全错误的,但是它演示了我希望完成的工作:

SELECT translation_result 
FROM (SELECT translation as translation_result FROM languages WHERE
label='your_account' AND language_id = 'zh')A
CASE  A.translation_result IS NOT NULL ELSE
(SELECT translation as translation_result FROM languages WHERE
label='your_account' AND language_id = 'en')B

Here's what I would do : 这就是我要做的:

SELECT (IFNULL(ZH.translation, EN.translation)) AS translation_result
FROM languages EN 
LEFT JOIN languages ZH ON EN.label=ZH.label AND ZH.language_id = 'zh'
WHERE EN.label='your_account' 
  AND EN.language_id = 'en'

Since english is the master language and always populated, you make your base query on the english records, which always returns something. 由于英语是主要语言并且总是被填充,因此您可以根据英语记录进行基本查询,该查询总是返回某些内容。 From what the english returns, you make a LEFT JOIN on the same table, for the same label but with diffrent language. 从英语返回的内容中,您可以在同一张桌子上为相同的标签但使用不同的语言进行LEFT JOIN If the JOIN is matching something (you don't have NULL ) you use this value 如果JOIN与某项匹配(您没有NULL ),则使用此值

But I think the query you shown is not a good example as it is not representative of what your end-queries on language table will be in the application. 但是我认为您显示的查询不是一个很好的例子,因为它不代表您在语言表上的最终查询将在应用程序中显示什么。 Normally you should make your "master" query on other table(s), and add LEFT JOIN queries on the language table(s) following the user's language You can add a real example and I'll adapt my answer to match it. 通常,您应该在其他表上进行“主”查询,并根据用户的语言在language表上添加LEFT JOIN查询。您可以添加一个真实的示例,我将调整其答案以使其匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM