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

时间:2020-05-26 09:33:41

标签: mysql

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

Query for latest price per seller per product

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

请参阅我提出的问题,因为我的原始帖子也不是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

1 个答案:

答案 0 :(得分:0)

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

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

为提高性能,请考虑在(seller, date)上建立索引。