I have the following query
SELECT
price
FROM prices
left join suppliers s on prices.id_supplier = s.id_supplier
AND prices.id_product = 57;
Table structures are as follows:
Suppliers:
id_supplier | name |
---|---|
1 | Supplier 1 |
2 | Supplier 2 |
3 | Supplier 3 |
Prices
id_pk | id_product | date | price | id_supplier |
---|---|---|---|---|
1 | 57 | 2022-12-29 | 4.99 | 1 |
2 | 57 | 2022-12-29 | 6.99 | 2 |
So based on the data above, I wish to create a query which fetches all prices for all supplier for a given product, even for Supplier 3 (which we do not have a price for in which case it should return 0)
Outpout I require is as follows:
id_supplier | price |
---|---|
1 | 4.99 |
2 | 6.99 |
3 | 0 |
Is this possible?
2
Answers
If I am understanding your problem correctly then this should work. Using case statement will get you price as 57 when price is 57 and when id_supplier IS NULL it will assign 0 to that row. Let me know if this helps.
Edit:
This query will select all the suppliers where price is either 57 or null.
You have the tables joined in the wrong order.
You want all rows from supplier, so that’s the LEFT table.