基于价格更新记录查询指定日期产品价格(MySQL 5.6.51)
问题描述
现有价格更新记录表结构及数据如下:
id Product Price price_update_date 1 Product 21.99 2022-11-09 6:32:11 2 Product 22.99 2022-09-27 9:06:14 3 Product 19.99 2022-07-10 6:27:49 4 Product 18.99 2022-05-24 7:31:20 5 Product 17.98 2022-04-21 8:59:18 6 Product 17.99 2022-02-02 8:33:48 7 Product 19.99 2021-12-20 8:43:41 8 Product 18.99 2021-11-29 2:31:00 9 Product 19.99 2021-10-11 7:42:17 10 Product 19.98 2021-06-10 5:11:03 11 Product 19.99 2021-02-25 2:23:45
需要查询指定日期(例如2022-10-01)对应的产品价格,使用MySQL 5.6.51版本,求实现方法。
解决方案
MySQL 5.6不支持窗口函数,因此需用传统查询方式实现,核心是找到指定日期前最近的价格更新记录,以下是几种可行方法:
方法1:子查询筛选最近更新日期
先通过子查询获取每个产品在指定日期前的最晚更新时间,再关联原表匹配对应价格:
SELECT t1.Product, t1.Price FROM price_table t1 INNER JOIN ( SELECT Product, MAX(price_update_date) AS latest_update FROM price_table WHERE price_update_date <= '2022-10-01' GROUP BY Product ) t2 ON t1.Product = t2.Product AND t1.price_update_date = t2.latest_update;
若只需查询单个产品,可在子查询和主查询中添加WHERE Product = '目标产品名'条件缩小范围。
方法2:自关联排除更晚更新记录
通过自关联,筛选出不存在同产品、更新时间更晚且不超过指定日期的记录(即当前记录为指定日期前最新):
SELECT t1.Product, t1.Price FROM price_table t1 LEFT JOIN price_table t2 ON t1.Product = t2.Product AND t2.price_update_date <= '2022-10-01' AND t2.price_update_date > t1.price_update_date WHERE t1.price_update_date <= '2022-10-01' AND t2.id IS NULL;
方法3:LIMIT单产品查询
如果仅需查询单个产品的价格,可直接排序后取第一条记录,写法更简洁:
SELECT Product, Price FROM price_table WHERE Product = 'Product' AND price_update_date <= '2022-10-01' ORDER BY price_update_date DESC LIMIT 1;
性能优化
为(Product, price_update_date)创建联合索引,能显著提升大表下的查询效率:
CREATE INDEX idx_product_update_date ON price_table(Product, price_update_date);
内容的提问来源于stack exchange,提问作者Antonych
相关产品推荐
相关产品推荐

