mysql - 查询每个卖家每个产品的最新价格
问题描述
我昨天问了一个非常相似的问题
它被标记为重复,但不幸的是,建议的答案对我没有帮助,因为情况不一样,或者我看不到解决方案。
请查看我的提炼问题,因为我的原始帖子也不是 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 可用
解决方案
一种选择是使用子查询进行过滤:
select t.*
from mytable t
where t.date = (select max(t1.date) from mytable t1.seller = t.seller)
对于性能,请考虑在(seller, date)
.
推荐阅读
- java - 为什么无法识别布尔值?
- sql - 跨行的 SQL 求和
- python - 从两个类继承(或)
- ios - 更新到 Xcode 12:无法将“DataRequest”类型的值转换为闭包结果类型“Void”
- css - 实现 Slick Slider 时使用混合模式中断的元素
- symfony - Api平台,部分数据相同时禁止POST方法
- javascript - 卡在 React-Native 推送通知中
- abap - 基于结构的 F4 搜索帮助。它是如何工作的?
- c# - 如何在不知道其名称的情况下删除索引?
- javascript - 在 JSON.stringify 之后发送和转换 Float32Array