带默认关系的左连接

t9aqgxwy  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(373)

需要找到所有单词的意大利语翻译,如果意大利语不存在,那么需要与西班牙语(默认语言)。我不能使用多个查询,以及where exists条件(技术限制)

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

翻译

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

结果:

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'))

这段代码返回所有我需要的,但我不能在我的情况下使用where exists条件

e5nszbig

e5nszbig1#

我会加入 words 桌上的table translations 表格两次,每种语言一次:

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'

相关问题