sql - Left join brainfart
问题描述
I seem to be thinking wrong today. I have two tables as follows
+--------+ +------------------------+
|person | |contact |
+--------+ +-----------------+------+
|id |name| |person_id |type | value|
+--------+ +------------------------+
|00 |a | |00 |phone |123 |
|01 |b | |00 |email |a@a.a |
|02 |c | |01 |phone |456 |
|03 |d | |02 |email |c@c.c |
+--------+ +------------------------+
and I need all persons and optionally their phone number, e.g.
+-----------+
|name |phone|
+-----------+
|a |123 |
|b |456 |
|c | |
|d | |
+-----+-----+
解决方案
您确实需要左连接,但您需要在连接条件中包含对电话类型的限制:
select p.*, c.value as phone
from person p
left join contact c
on c.person_id = p.id
and c.type = 'phone'
如果您将限制c.type = 'phone'
放入where
子句中,则会将外部联接重新转换为内部联接。
推荐阅读
- javascript - 使用 TypeScript 和 Axios 进行 http 调用时如何选择响应正文中的某些字段
- php - Codeigniter URL 中的双斜杠问题
- time-complexity - 哈希表时间复杂度混淆
- html - 如何通过xpath在第一个子节点之前获取节点的文本?
- amazon-web-services - 查找 executionRoleArn、taskRoleArn 的值
- java - Java:处理文件时Arraylist超出范围
- laravel - 使用 Laravel Sanctum 进行 Vue SPA 身份验证
- javascript - 如何在反应中通过多个组件传递数据?
- python - OperatorNotAllowedInGraphError:不允许迭代 `tf.Tensor`:AutoGraph 确实转换了此函数
- swift - 布尔函数返回默认值,直到在 Firebase DB XCode Swift 中检查实际值