【问题标题】:How to join where some values only exist in one table?如何加入某些值仅存在于一个表中?
【发布时间】:2020-09-18 11:16:53
【问题描述】:

我有两张表,看起来像这样:

Table_1:

Shop_ID | Offer_ID | Metric_1
--------|----------|---------
AAA     | 111      | 1
AAA     | 222      | 2
BBB     | 222      | 3

Table 2:

Shop_ID | Offer_ID | Metric_2
--------|----------|---------
AAA     | 111      | 1
AAA     | 222      | 2
BBB     | 111      | 3
CCC     | 111      | 4
CCC     | 222      | 5

我想将它们加入一个组合数据集,就像这样。结果需要同时显示所有商店及其优惠的这两个指标,即使包含商店和优惠组合的行仅出现在其中一个表中也是如此。

Shop_ID | Offer_ID | Metric_1 | Metric_2
--------|----------|----------|---------
AAA     | 111      | 1        | 1
AAA     | 222      | 2        | 2
BBB     | 111      | NULL     | 3
BBB     | 222      | 3        | NULL
CCC     | 111      | NULL     | 4
CCC     | 222      | NULL     | 5

请问有人知道怎么做吗?

【问题讨论】:

    标签: sql join db2


    【解决方案1】:

    你想要一个FULL JOIN

    select coalesce(t1.shop_id, t2.shop_id), coalesce(t1.offer_id, t2.offer_id),
           t1.metric_1, t2.metric_2
    from table_1 t1 full join
         table_2 t2
         on t1.shop_id = t2.shop_id and t1.offer_id = t2.offer_id;
    

    或者使用USING简单一点:

    select shop_id, offer_id, t1.metric_1, t2.metric_2
    from table_1 t1 full join
         table_2 t2
         using (shop_id, offer_id);
    

    【讨论】:

      猜你喜欢
      • 2013-06-25
      • 1970-01-01
      • 2022-01-01
      • 2010-10-05
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多