I want to add a subset of a table (t2)
to another table (t1)
for each customer_id
once.
t1
represents ordered materials. t2
represents a static table representing high-seller materials.
The goal is to create a table with material lists for each customer. (t2)
does not include any customer_id
reference but a region_id
key.
Basically what I need is "add this subset material list to your existing material list for each customer
based on his region"
I can't figure out how to join/union
those tables without a customer_id
, as I will get duplicated entries.
t1
looks like this:
Customer_id | region_id | material_id |
---|---|---|
155 | NAM | AA-123-526 |
155 | NAM | AA-425-123 |
157 | NAM | AA-123-623 |
157 | NAM | AA-612-244 |
158 | SOA | AA-123-456 |
158 | SOA | AA-655-876 |
t2
looks like this:
region_id | material_id |
---|---|
NAM | BB-724-623 |
NAM | BB-421-125 |
DACH | BB-123-622 |
DACH | BB-421-231 |
SOA | BB-123-551 |
SOA | BB-421-125 |
desired output:
Customer_id | region_id | material_id |
---|---|---|
155 | NAM | AA-123-526 |
155 | NAM | AA-425-123 |
155 | NAM | BB-724-623 |
155 | NAM | BB-421-125 |
157 | NAM | AA-123-623 |
157 | NAM | AA-612-244 |
157 | NAM | BB-724-623 |
157 | NAM | BB-421-125 |
158 | SOA | AA-123-456 |
158 | SOA | AA-655-876 |
158 | SOA | BB-123-551 |
158 | SOA | BB-421-125 |
Sample data
SELECT * FROM t1
SELECT * FROM t2
Solution
SELECT t1.Customer_id, t1.region_id, t1.material_id FROM t1
UNION ALL
SELECT DISTINCT t1.Customer_id, t2.region_id, t2.material_id
FROM t2 INNER JOIN t1 ON t2.region_id = t1.region_id
ORDER BY t1.Customer_id