Rolando Cruz
Rolando Cruz

Reputation: 2784

selecting the least value in a joined table

Basically I have product and several models for those products. Each model has a price.

This is what I intended to do:

Mark a product as featured, then have it's title, description, number 1 image's thumbnail and the price for the cheapest model

This is my current query:

SELECT
  product.title,
  product.url_name,
  product.description,
  price.price,
  image.thumbnail
FROM
  mps_contents AS product
  LEFT OUTER JOIN
    mps_contents AS image 
    ON
      image.page_id = product.content_id AND
      image.display_order = '1' AND
      image.resource_type = 'image'
  LEFT OUTER JOIN
    mps_contents AS model 
    ON
      product.content_id = model.page_id
  INNER JOIN
    mps_product_info AS price
    ON
      model.content_id = price.content_id
WHERE
  product.active = '1' AND
  product.resource_type = 'product' AND
  product.featured = '1'
ORDER BY RAND( )
LIMIT 3

You may see that my query cannot do the price sorting, I hope somebody could help me with that. An additional problem that I encounter is if I have multiple models for a product. I end up getting a set that has prices for 2 models from a single product when the intent is to have the 1 price for each product.

I am aware of the issue with ORDER BY RAND() but I will ignore it since I don't think this site will have more that 50 products.

Upvotes: 2

Views: 64

Answers (1)

Matt MacLean
Matt MacLean

Reputation: 19658

I think something like this should work....

SELECT
  product.title,
  product.url_name,
  product.description,
  A.price,
  image.thumbnail
FROM
  mps_contents AS product
  LEFT OUTER JOIN
    mps_contents AS image 
    ON
      image.page_id = product.content_id AND
      image.display_order = '1' AND
      image.resource_type = 'image'
  LEFT OUTER JOIN (
      SELECT price.price 
      FROM mps_contents AS model 
      JOIN mps_product_info price ON (model.content_id = price.content_id) 
      WHERE model.page_id = product.content_id 
      ORDER BY price.price
      LIMIT 1
  ) AS A
WHERE
  product.active = '1' AND
  product.resource_type = 'product' AND
  product.featured = '1'
ORDER BY RAND( )
LIMIT 3

Upvotes: 3

Related Questions