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;
Mysql get current highest priced items
-
01-09-2022 - |
Question
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
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow