sql查询 - 在WHERE子句中的IF EXIST

时间:2014-01-08 10:20:36

标签: mysql sql select join where

我有一个像

的查询
SELECT * 
FROM aTable
LEFT JOIN aTableTranslate
ON aTable.id = aTableTranslate.aTable_id
WHERE
 aTableTransalte.language like 'en'

问题是......

有没有办法像

那样进行过滤

...

WHERE
 aTableTranslate.language like (IF EXIST_A_FIELD_FOR 'en' THEN 'en' ELSE IF EXIST_A_FIELD_FOR 'jp' THEN 'jp' OR 'cn')

我想用1.访问者的语言>显示列表2.英语...>或默认语言。

可以通过查询吗?

2 个答案:

答案 0 :(得分:2)

您可以单独加入翻译表,然后使用COALESCE选择第一个非NULL翻译,如下所示:

SELECT a.*, COALESCE(t1.translation, t2.translation, t3.translation) as translation
FROM aTable a
LEFT JOIN aTableTranslate t1 ON aTable.id = t1.aTable_id AND t1.language like 'en'
LEFT JOIN aTableTranslate t2 ON aTable.id = t2.aTable_id AND t2.language like 'jp'
LEFT JOIN aTableTranslate t3 ON aTable.id = t3.aTable_id AND t3.language like 'cn'

答案 1 :(得分:0)

试试这个:

SELECT a.*, COALESCE(IF(t1.language = 'en', t1.translation, NULL), 
                     IF(t1.language = 'jp', t1.translation, NULL), 
                     IF(t1.language = 'cn', t1.translation, NULL)
                   ) AS translation
FROM aTable a
LEFT JOIN aTableTranslate t1 ON aTable.id = t1.aTable_id AND t1.language IN ('en', 'jp', 'cn')