Search code examples
mysqlgroupwise-maximum

Mysql get current highest priced items


I'm looking to get the 20 highest current priced products.

I have a product table that has many prices table.

products: id

prices: id, product_id, value, change_date

Here's an example.

Product: 1
  price: 11, change_date 12/1/2013, value: $10
  price: 12, change_date 11/1/2013, value: $15
Product: 2
  price: 21, change_date: 12/1/2013, value: $12
  price: 22, change_date: 11/1/2013, value: $10
Product: 3
  price: 31, change_date: 11/1/2013, value: $20

The highest "current" priced products would be 3, than 2, than 1

How would I execute this in MySQL?

I tried the following but the value column doesn't match the value associated with the max(change_date) row. So the sort is busted as a result.

SELECT id, product_id, price, max(change_date) 
FROM prices
GROUP BY product_id
ORDER BY value DESC
LIMIT 20

Thanks!


Solution

  • SELECT id, product_id, value, change_date
    FROM prices
    JOIN (SELECT product_id, MAX(change_date) AS recent_date
          FROM prices
          GROUP BY product_id) AS most_recent
      ON prices.product_id = most_recent.product_id
        AND prices.change_date = most_recent.recent_date
    ORDER BY value DESC
    LIMIT 20;