MySQL 5.7 |分组 |截然不同 |聚合错误
MySQL 5.7 | group by | distinct | aggregation error
我正在使用 MySQL 5.7.
我有一个 table 如下:
--------------------------------------------------
| 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
选项并且它有效,但我不想这样做,我想要正确的方式(新方式)。
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
我正在使用 MySQL 5.7.
我有一个 table 如下:
--------------------------------------------------
| 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
选项并且它有效,但我不想这样做,我想要正确的方式(新方式)。
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