I'm struggling with a query. I need to create a view based on this query.
I've got 3 tables: seller, item, seller_item
Seller table
| name | id |
|---|---|
| S1 | 1 |
| S2 | 2 |
| S3 | 3 |
Item table
| name | id | price |
|---|---|---|
| I1 | 1 | 50 |
| I2 | 2 | 100 |
Seller_Item table
| seller_id | item_id | price |
|---|---|---|
| 1 | 1 | 75 |
| 2 | 1 | 25 |
View I'd like to obtain
| nome | item | price |
|---|---|---|
| S1 | I1 | 75 |
| S1 | I2 | 100 |
| S2 | I1 | 25 |
| S2 | I2 | 100 |
| S3 | I1 | 50 |
| S3 | I2 | 100 |
Basically, if the item is not present in the table seller_item I want to insert the default value coming from the item table otherwise the one from the seller_item table.
I was able to achieve something similar using WHERE NOT EXIST, but only when I ask for a specific seller id, instead, here, I want to have the list of all the sellers with all items.
Thank you.
----- SOLUTION -----
Thank you for your quick answers.
Just few minutes after I posted the question I found the solution. It was a lot more verbose than what I was able to find thanks your suggestions.
The final query (with all the values I need) is this one:
SELECT
S.name AS name,
I.name AS item,
IF(SI.visible = 0, SI.visible, I.visible) AS visible,
IF(COALESCE(SI.price, 0) = 0, I.price, SI.price) AS price FROM seller S JOIN item I LEFT JOIN seller_item SI ON S.id = SI.seller_id AND I.id = SI.item_id ORDER BY 1, 2
Thank you again!