我正在使用MySQL 5.7。
我有一张表如下:
--------------------------------------------------
| id | currentcy_id | rate | created_at |
--------------------|------|---------------------|
| 1 | 1 | 1 | 2017-11-07 23:19:48 |
| 2 | 2 | 2 | 2017-11-07 23:20:48 |
| 3 | 3 | 4 | 2017-11-07 23:21:48 |
| 4 | 1 | 2 | 2017-11-07 23:22:48 |
--------------------------------------------------
我想通过执行以下操作来获取每个不同currency_id
的最新值:
SELECT `currentcy_id`, `rate`, MAX(`created_at`)
FROM `currency_reates`
GROUP BY (`currentcy_id`)
我也尝试了DISTICT功能:
SELECT DISTINCT(`currentcy_id`), `rate`, MAX(`created_at`)
FROM `currency_reates`
我从两个有关聚合的查询中都收到错误。
注意:我在MySQL中禁用了STRICT
选项并且它有效,但我不想这样做,我想要正确的方式(新的)。
答案 0 :(得分:1)
SELECT C.`currentcy_id`, C.`rate`, C.`created_at`
FROM `currency_reates` C
JOIN ( SELECT `currentcy_id`, MAX(`created_at`) as m_date
FROM `currency_reates`
GROUP BY (`currentcy_id`)
) as T
ON C.`currentcy_id` = T.`currentcy_id`
AND C.`created_at` = T.m_date