Reputation: 1732
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
Upvotes: 2
Views: 165
Reputation: 311863
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'
Upvotes: 5