Jump to content

Product table, options table. Select all products with their cheapest option?


zq29

Recommended Posts

Confusing title? I couldn't explain it any other way in such a small field! Ok, here goes...

 

product

id, name, description

 

product_option

id, product, name, price

 

I'm trying to display a list of products, each with its cheapest option as the display price.

 

SELECT p.*, po.`price` 
FROM `product` as p
LEFT JOIN `product_option` AS po ON p.`id` = po.`product`
ORDER BY po.`price`

 

This query returns duplicate data, one almost identical row per option, with the price differing. To be expected. I'm having difficulty only returning one row per product, with the price of the cheapest option. I tried adding a GROUP BY p.`id`, and this cut it down to one row per product, but it was not displaying the cheapest price, it displayed the price with the lowest id in the product_option table. Ordering before Grouping returns errors...

 

Am I attacking the task from the wrong direction, can someone point me in the right way? Many thanks.

There are a variety of ways to do this... all of them require you to find the uid of the po record with the lowest price *first*, and then join them back.

 

SELECT p.*, po.cheapest
FROM product AS p
LEFT JOIN 
( SELECT product, MIN(price) AS cheapest FROM product_options GROUP BY product ) AS po
ON ( po.product = p.id )

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.