Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fetch price for all suppliers in joined table

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

You have the tables joined in the wrong order.

You want all rows from supplier, so that’s the LEFT table.

SELECT
  s.*,
  COALESCE(p.price, 0)
FROM
  suppliers   s
LEFT JOIN
  prices      p
    ON  p.id_supplier = s.id_supplier
    AND p.id_product  = 57
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading