sql - 在 SQL 中合并来自两个数据库表的结果
问题描述
我有两个数据库表,都包含一个名为“direction”的列,一个包含另一个的外键。我想查询一次数据库,给我一个合并的结果集,其中包含两个表中的所有数据。
对于第一个表中的一行,不能保证第二个表中会有互补的条目。在这种情况下,我只想让单元格为空白。
两个表的提取示例如下所示
Table 1
case_id direction speed
1 000 1.22
1 090 0.97
1 180 0.17
1 270 2.50
2 2.14
Table 2
tbl1_case_id direction probability
1 000 0.175
1 090 0.275
1 180 0.555
1 270 0.145
我想要的结果集如下:
Results
case_id direction speed probability
1 000 1.22 0.175
1 090 0.97 0.275
1 180 0.17 0.555
1 270 2.50 0.145
2 2.14
是否有一个有效的 SQL 查询可以让我产生这个?
解决方案
如果您想要两个表中的所有行,请使用full join
:
select id, direction, t1.speed, t2.probability
from table1 t1 full join
table2 t2
using (id, direction);
您的示例结果和解释表明left join
:
select id, direction, t1.speed, t2.probability
from table1 t1 left join
table2 t2
using (id, direction);
但是,在这种情况下,330 的值将是空白的。
推荐阅读
- domain-driven-design - DDD - 由于聚合数据不同而导致多个有界上下文?
- python - 如何在 GAE 应用程序中执行异步 api 请求?
- javascript - 无法解构“未定义”或“空”的属性“变量名称”
- javascript - Native Base Toast - TypeError:TypeError:TypeError:null不是对象(评估'this.toastInstance._root.getModalState')
- dynamics-crm - 如何防止从仪表板网格创建新记录?
- r - 在 R 中保持 ggplot 中的宽度不变
- google-data-studio - 如何在 Google Data Studio 连接器中获取查看者电子邮件?
- c - 简单的 IF Else,但是当我尝试生成错误时会导致命令框崩溃
- collections - 如何按其中一个字段索引一组记录?
- angular - 为复选框数组定义 [(ngModel)] 以使用表单获取不同 JSON 格式的输出