【问题标题】:find difference between two tables with different keys查找具有不同键的两个表之间的差异
【发布时间】:2021-10-08 00:07:38
【问题描述】:

我的表 A 看起来像这样:

id name
a1 A1
a2 A2
b2 B2

和看起来像这样的表 B:

volume_id volume_name
a1 A1
b1 B1
b2 B2

我想进行一个查询(或多个),该查询将为我提供表 A 中存在但不存在于表 B 中的 id(或 volume_id,因为它们代表相同的事物),反之亦然。

我使用 psql 作为我的 postgres cli。

【问题讨论】:

    标签: sql postgresql left-join exists full-outer-join


    【解决方案1】:

    你可以使用full join:

    select a.id, b.volume_id
    from a full join
         b
         on a.id = b.volume_id
    where a.id is null or b.volume_id is null;
    

    这会将结果放在单独的列中,这样您就可以看到缺少哪些。

    【讨论】:

      【解决方案2】:

      您可以使用 FULL JOIN 来显示 A 列中存在但 B 列中不存在的值。

      select t1.id, t2.volumeid from a as t1 full join b as t2 on t1.id=t2.volumeid;
      

      作为旁注,您也可以在类似情况下使用 LEFT JOIN 来完成此操作,但您需要确保左侧的列包含 a 和b,否则您会发现表格中的额外值在右侧列中时不会显示。

      这里不是这种情况,即表 a 不包含值 b1,因此这就是为什么您必须在此特定示例中使用完全连接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-04
        相关资源
        最近更新 更多