我有下表
table prices
col id
col price
col currency_id
col timestamp (unix)
我想按货币 ID 对货币进行分组,并仅根据时间戳显示最新记录。
我有以下查询,它正确分组但没有获取最新记录,似乎总是获取表中的第一行而不是最后一行。
SELECT
id,
price,
currency_id,
timestamp
FROM prices
GROUP BY currency_id
ORDER BY timestamp DESC
我确实很懒,尝试这样做,获取最后 6 条记录,但顺序并不总是相同,这意味着每次添加新货币(当前为 6)时我都必须修改查询。
SELECT
id,
price,
currency_id,
timestamp
FROM prices
ORDER BY timestamp DESC
LIMIT 6
我已经有几年没有做过任何 MySQL 了,感觉这是最简单的事情,哈哈:(
最佳答案
这是一个要测试的sqlfiddle http://sqlfiddle.com/#!9/2a4e63/3
从这里开始:
SELECT currency_id,
Max(timestamp)
FROM prices
GROUP BY currency_id
然后将其集成到主查询中:
SELECT *
FROM prices
WHERE ( currency_id, timestamp ) IN (SELECT currency_id,
Max(timestamp)
FROM prices
GROUP BY currency_id)
关于MySQL 按最新值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48134969/