Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
827 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...