MySQL join - 三个表,返回null为空

时间:2011-06-23 16:36:07

标签: mysql join

我有以下架构:

phrase (in U.S. English):  translation:                                 code_value:
----------------------     -----------------------------------------    ------------------------------
| phrase_id | phrase |     | phrase_id | translation | language_cd |    | code class    | code value |
----------------------     -----------------------------------------    ------------------------------
|     1     | cheese |     |     1     |   fromage   |    FR       |    | LANGUAGE_CD   |    FR      |
----------------------     -----------------------------------------    | LANGUAGE_CD   |    DE      |
                                                                        | LANGUAGE_CD   |    ES      |
                                                                        ------------------------------

这个数据集的作用是,对于给定的美国英语短语,它将为您提供三种语言(法语,德语和西班牙语)的相应翻译(至少在我们的网络应用程序的上下文中 - 我们不是试图成为谷歌翻译或任何东西)。

我要做的是获取给定短语的所有翻译列表,如果不存在给定目标语言的翻译,我希望它返回NULL。

到目前为止,我的查询是:

SELECT phrase.phrase_id, phrase.string orig_phrase, code_value.code_value, translation.string as trans_phrase
FROM phrase, translation, code_value
WHERE code_value.code_class = 'LANGUAGE_CD' AND translation.phrase_id = phrase.phrase_id
ORDER BY orig_phrase;

返回:

-------------------------------------------------------
| phrase_id | orig_phrase | code_value | trans_phrase |
-------------------------------------------------------
|    1      | cheese      | FR         | fromage      |
|    1      | cheese      | DE         | fromage      |
|    1      | cheese      | ES         | fromage      |
-------------------------------------------------------

但我打算让它返回的是:

-------------------------------------------------------
| phrase_id | orig_phrase | code_value | trans_phrase |
-------------------------------------------------------
|    1      | cheese      | FR         | fromage      |
|    1      | cheese      | DE         | <NULL>       |
|    1      | cheese      | ES         | <NULL>       |
-------------------------------------------------------

我知道我需要一个LEFT或RIGHT JOIN来获取NULL值,但我似乎无法弄清楚如何编写它。

当这一切都说完了,显然我们也会在那里有德语和西班牙语的翻译,我需要它们来匹配,但NULL值的目的是清楚地向我们展示我们使用的语言还没有翻译给定的短语。

2 个答案:

答案 0 :(得分:1)

SELECT phrase.phrase_id, phrase.string orig_phrase, code_value.code_value, translation.string as trans_phrase
FROM phrase
inner join  translation on (translation.phrase_id = phrase.phrase_id)
left join code_value on (code_value.code_value=translation.language_cd)
WHERE code_value.code_class = 'LANGUAGE_CD' 
ORDER BY orig_phrase;

答案 1 :(得分:1)

你是对的,你需要一个LEFT或RIGHT加入。这应该有效:

SELECT `p`.`phrase_id`, `p`.`phrase` `orig_phrase`, `c`.`code_value`, `t`.`translation` `trans_phrase`
FROM `phrase` `p`
INNER JOIN (
    SELECT `code_value` 
    FROM `code_value` 
    WHERE `code_class` = 'LANGUAGE_CD'
) `c`
LEFT JOIN `translation` `t` ON `p`.`phrase_id` = `t`.`phrase_id` AND `c`.`code_value` = `t`.`language_cd`;

希望这有帮助。