【发布时间】:2018-05-03 17:40:23
【问题描述】:
我使用的是 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 选项并且它可以工作,但我不想这样做,我想要正确的方式(新的方式)。
【问题讨论】:
-
rate也需要聚合函数或者在group by -
@LONG,根据
created_at,我需要最后一个rate。 -
我明白了,那你可以试试:
SELECT currentcy_id, MAX(rate) FROM currency_reates A GROUP BY (currentcy_id) WHERE created_at = (SELECT MAX(created_at ) FROM currency_reates as B WHERE B.currentcy_id = A.currentcy_id),这不是得到结果的最佳查询,但可能更容易理解 -
select * from currency_reates where id = (select id from currency_reates order by end_date desc limit 1);
标签: mysql group-by distinct aggregate-functions mysql-5.7