I have 2 tables below:
table1
store_name | store_code | sub_channel |
---|---|---|
A | 12345 | C021 |
B | 56789 | C021 |
C | 10000 | C021 |
table2
product_code | store_code | sub_channel | qty |
---|---|---|---|
X1 | 12345 | 10 | |
X1 | C021 | 20 | |
X2 | 12345 | C021 | 50 |
X3 | 56789 | C021 | 20 |
X4 | C021 | 40 | |
X5 | 56789 | 100 |
I want to fetch the data from table2 based on store_code or sub_channel but only showing data only if there is the data based on store_code then select only from store_code and if it’s not then select from sub_channel.
Here is my query:
SELECT t1.store_name, t2.*
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t2.store_code = t1.store_code OR t2.sub_channel = t1.sub_channel
ORDER BY t1.store_name, t2.product_code
I got result as below:
store_name | product_code | store_code | sub_channel | qty |
---|---|---|---|---|
A | X1 | 12345 | 10 | |
A | X1 | C021 | 20 | |
A | X2 | 12345 | C021 | 50 |
A | X3 | 56789 | C021 | 20 |
A | X4 | C021 | 40 | |
B | X1 | C021 | 20 | |
B | X2 | 12345 | C021 | 50 |
B | X3 | 56789 | C021 | 20 |
B | X4 | C021 | 40 | |
B | X5 | 56789 | 100 | |
C | X1 | C021 | 20 | |
C | X2 | 12345 | C021 | 50 |
C | X3 | 56789 | C021 | 20 |
C | X4 | C021 | 40 |
What I want to achieve here as below:
store_name | product_code | store_code | sub_channel | qty |
---|---|---|---|---|
A | X1 | 12345 | 10 | |
A | X2 | 12345 | C021 | 50 |
B | X3 | 56789 | C021 | 20 |
B | X5 | 56789 | 100 | |
C | X1 | C021 | 20 | |
C | X2 | 12345 | C021 | 50 |
C | X3 | 56789 | C021 | 20 |
C | X4 | C021 | 40 |
Is there any way to achieve this and which additional code to add up in my query to achieve this?
2
Answers
Why not UNION ?
I think we can do this with two
LEFT JOIN
s:The first join attempts to match on the store code; the second join targets the sub-channel – with an additional condition that ensures that only rows that did no match on the first join are taken into account.
Demo on DB Fiddle: