Jump to content

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


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 )

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.