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!

4

2 回答 2

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;
于 2013-12-13T00:28:06.263 回答
1

在 where 子句中按每个产品的 max(change_dt) 过滤。

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;

注意:我将prices表格设为单数形式 price

SQL小提琴: http ://sqlfiddle.com/#!2/f6dc0/2

SQL Fiddle 仅将价格限制为 1,因为我不想为测试数据制定 20 多个价格。

于 2013-12-13T00:17:10.290 回答