如何加入一些值只存在于一个 table 中的地方?

How to join where some values only exist in one table?

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

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

请问有人知道怎么做吗?

你想要 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);