I have two tables, which look something like this:
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
I want to join them into one combined dataset, like this. The result needs to show both of the two metrics for all shops and their offers, even when the row containing that combination of store & offer is only present in one of the tables.
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
Does anyone know how to do this, please?
You want a 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;
Or a bit simpler using 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.