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

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

mysql - Left join with default relation

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

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

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...