我有一个包含两个链接表(产品和价格历史记录)的MySQL数据库。它们由一个productID字段链接。每次产品的价格发生变化,我都会创建一个新的历史记录。产品的最新历史记录是最新的价格。我还将当前价格存储在产品表中。我想运行一个报告,在那里我可以检索第二次的价格历史记录,以便我可以比较当前和最后的价格。我尝试了下面的sql查询,它返回最新的价格历史记录,即当前价格。我怎样才能获得第二次最近的价格历史记录?对于较新的记录,historyID将更高,因为它是自动增量和价格历史记录,updateTime也将是更新记录的最新版本,因此这可能是一种排序方法。谢谢!
SELECT
product.code, product.currentPrice, priceHistory.price,
product.url, product.manuID, product.lastSeenTime,
priceHistory.updateTime, product.dateAdded,
priceHistory.historyID
FROM product, priceHistory
WHERE product.idProduct = priceHistory.productID
GROUP BY priceHistory.productID
HAVING count(*) > 1
ORDER BY `product`.`lastSeenTime` DESC发布于 2019-08-10 22:35:06
您可以使用ROW_NUMBER()窗口函数根据任意顺序为行分配编号。一旦你这样做了,你就可以简单的过滤这个数字。
例如:
with
h as (
select *,
row_number() over(partition by productid order by updatetime desc) as rn
from pricehistory
)
select
p.code,
p.currentprice,
h.price,
p.url,
p.manuid,
p.lastseentime,
h.updatetime,
p.dateadded,
h.historyid
from product p
left join h on h.productid = p.productid and h.rn = 2编辑
如果不能使用CTE,则可以使用表表达式重写查询,如下所示:
select
p.code,
p.currentprice,
h.price,
p.url,
p.manuid,
p.lastseentime,
h.updatetime,
p.dateadded,
h.historyid
from product p
left join (
select *,
row_number() over(partition by productid order by updatetime desc) as rn
from pricehistory
) h on h.productid = p.productid and h.rn = 2https://stackoverflow.com/questions/57445885
复制相似问题