首页 > 解决方案 > 在 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 查询可以让我产生这个?

标签: sqlpostgresql

解决方案


如果您想要两个表中的所有行,请使用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 的值将是空白的。


推荐阅读