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)
词
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 条件
This code return all I need, but I can't use where exists conditions in my situation
推荐答案
我会在 translations 表中加入 words 表两次,每种语言一次:
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'
这篇关于具有默认关系的左连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有默认关系的左连接
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
