MySQL选择包含子数据的所有父数据(包括空值)

时间:2015-11-09 19:53:00

标签: mysql join

我有3张桌子:

  • :单词的ID和单词本身
  • word_item :按字ID识别字词。
  • word_item_translate :使用de,fr,it等语言代码翻译单词定义

我当前的应用需要检索所请求单词的定义。例如:

用西班牙语

创建Word caballo
SELECT word.id_word, word_item.id_item, word_item.definition  
FROM word 
INNER JOIN word_item ON word.id_word = word_item.id_word 
WHERE word.lang = "es" 
AND word.word LIKE "caballo" 
ORDER BY word_item.votes DESC, word_item.id_item

http://sqlfiddle.com/#!9/d0a44/4

这很棒!但该应用还需要检索定义翻译,所以...

Word * caballo"西班牙语与德语翻译

SELECT word.id_word, word_item.id_item, word_item.definition, word_item_translate.translation 
FROM word 
INNER JOIN word_item ON word.id_word = word_item.id_word 
LEFT JOIN word_item_translate 
ON word_item_translate.id_item = word_item.id_item 
AND (word_item_translate.id_item_translate OR word_item_translate.id_item_translate IS NULL) 
WHERE word.lang = "es" 
AND word.word LIKE "caballo" 
AND (word_item_translate.lang = "de" OR word_item_translate.lang IS NULL) 
ORDER BY word_item.votes DESC, word_item.id_item

http://sqlfiddle.com/#!9/d0a44/5

这不太好用。正如你所看到的,原来的单词" caballo"在word_item内有11个不同的定义。这11条记录中只有8条已翻译成德文。但是,第二个查询应显示11条记录,如果3条记录没有翻译,translation列应显示NULL的值。

1 个答案:

答案 0 :(得分:2)

我认为您对如何使用LEFT JOIN感到困惑。以下应该有效:

SELECT word.id_word, word_item.id_item, word_item.definition, word_item_translate.translation  
FROM word 
INNER JOIN word_item ON word.id_word = word_item.id_word
LEFT JOIN word_item_translate ON
word_item_translate.id_item = word_item.id_item
AND word_item_translate.lang = 'de'
WHERE word.lang = 'es' 
AND word.word LIKE 'caballo' 
ORDER BY word_item.votes DESC, word_item.id_item