我有下表
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已经有几年了,感觉这是最简单的事情lol :(
答案 0 :(得分:1)
这是一个测试http://sqlfiddle.com/#!9/2a4e63/3
的sqlfiddle从这开始:
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)