1

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!

Strawberry
  • 33,750
  • 13
  • 40
  • 57
alaup
  • 61
  • 1
  • 8

2 Answers2

2
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;
AgRizzo
  • 5,261
  • 1
  • 13
  • 28
1

In the where clause filter by the max(change_dt) for each product.

select id, product_id, price, change_dt
from price p
where change_dt in (select max(change_dt) from price where product_id = p.product_id)
order by price
limit 20;

NOTE: I made the prices table its singular form price.

SQL Fiddle: http://sqlfiddle.com/#!2/f6dc0/2

The SQL Fiddle only limits the prices to 1 since I didn't want to make 20+ prices for test data.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • concise solution. I hadn't used sqlfiddle before, thanks for the tip – alaup Dec 13 '13 at 03:48
  • one thing worth noting is this example is more concise but seems to run slower than other solutions. about 10 seconds compared to 1 second on a million price rows. – alaup Dec 13 '13 at 17:08