Left join with default relation

坚强是说给别人听的谎言 提交于 2019-12-02 05:48:39

问题


Need to find all words with their Italian translation, if Italian doesn't exist, then need with Spanish (default language). I can`t use more than one query, and where exists condition(technical limitations)

Words

id|name
-------
 1|Dog
 2|Cat

Translations

id|word_id|translation|language
-------------------------------
 1|      1|      Perro|es
 2|      1|      Cane |it
 3|      2|      Gatto|es

Result:

id|name|translation|language
 1| Dog|       Cane|it
 2| Cat|      Gatto|es

SELECT * FROM words LEFT JOIN translation ON words.id = translation.word_id WHERE language = 'it' OR (language = 'es' AND NOT EXISTS(SELECT * FROM translation WHERE word_id = words.id AND language = 'it'))

This code return all I need, but I can't use where exists conditions in my situation


回答1:


I'd join the words table on the translations table twice, once for each language:

SELECT    w.id, 
          w.name,
          COALESCE(it.translation, es.translation) AS translation,
          COALESCE(it.language, es.language) AS language
FROM      words w
LEFT JOIN translation it ON w.id = it.word_id AND it.language = 'it'
LEFT JOIN translation es ON w.id = es.word_id AND es.language = 'es'


来源:https://stackoverflow.com/questions/51046859/left-join-with-default-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!