首页 > 解决方案 > 查询每个卖家每个产品的最新价格

问题描述

我昨天问了一个非常相似的问题

查询每个卖家每个产品的最新价格

它被标记为重复,但不幸的是,建议的答案对我没有帮助,因为情况不一样,或者我看不到解决方案。

请查看我的提炼问题,因为我的原始帖子也不是 100% 正确的。

我有一个如下所示的数据库表:

id    product_id     product_name     price     date            seller
1     646            Product 1        1         2020-05-20      Seller-A
2     1554           Product 2        1.50      2020-05-23      Seller-B
3     646            Product 1        2         2020-05-22      Seller-C
4     646            Product 1        2.5       2020-05-23      Seller-A

因此,我想根据每个 product_id 的日期以及每个卖家的日期获取最新信息。

 2     1554           Product 2        1.50      2020-05-23      Seller-B 
 3     646            Product 1        2         2020-05-22      Seller-C
 4     646            Product 1        2.5       2020-05-23      Seller-A

-> 不应返回结果 1,因为卖方 A 的价格更新为 id 4

我有以下查询适用于 1 个产品 ID:

SELECT * FROM (SELECT * FROM `table` WHERE 1 ORDER BY `date` DESC) t2 WHERE product_id = 646 GROUP BY `seller`

我应该如何构建查询以获取多个 id 的结果。目前,它只会返回每个可用卖家的结果,但无论有多少产品 id 可用

标签: mysql

解决方案


一种选择是使用子查询进行过滤:

select t.*
from mytable t
where t.date = (select max(t1.date) from mytable t1.seller = t.seller)

对于性能,请考虑在(seller, date).


推荐阅读