我有一张这样的表:
------------------------------------------------- id | race_id | heat | updated_at ------------------------------------------------- 28952 189 1 2017-06-24 19:57:44.433431 28956 189 1 2017-06-24 20:33:49.984958 28958 189 1 2017-06-24 21:43:59.538041 28953 189 2 2017-06-24 19:57:45.309102 28957 189 2 2017-06-24 20:36:41.725912 28961 189 2 2017-06-24 21:46:39.677080 28954 189 3 2017-06-24 19:57:46.142353 28959 189 3 2017-06-24 21:44:00.651232 28964 189 3 2017-06-24 23:13:24.172765 28969 189 3 2017-06-25 01:01:25.445597 28955 189 4 2017-06-24 19:57:47.056272 28962 189 4 2017-06-24 21:46:40.839643 28965 189 4 2017-06-25 01:00:44.736679 28966 189 4 2017-06-25 01:01:04.010346 28960 189 5 2017-06-24 21:44:02.443140 28963 189 5 2017-06-24 21:46:41.861473 28968 189 6 2017-06-25 01:01:06.028000 28971 189 6 2017-06-25 01:01:28.445862 28967 189 8 2017-06-25 01:01:05.198073 28970 189 8 2017-06-25 01:01:27.533253
但是我试图通过race_id和heat来分组每个组的最新时间戳。我希望看到这样的事情:
------------------------------------------------- id | race_id | heat | updated_at ------------------------------------------------- 28958 189 1 2017-06-24 21:43:59.538041 28961 189 2 2017-06-24 21:46:39.677080 28969 189 3 2017-06-25 01:01:25.445597 28966 189 4 2017-06-25 01:01:04.010346 28963 189 5 2017-06-24 21:46:41.861473 28971 189 6 2017-06-25 01:01:28.445862 28970 189 8 2017-06-25 01:01:27.533253
我正在尝试使用
select id, race_id, heat, updated_at from heats where race_id = 189 group by race_id, heat having updated_at = max(updated_at) order by heat asc;但我没有得到任何结果。
答案 0 :(得分:0)
不,group by
是错误的做法。只需使用与最新时间戳的比较:
select h.*
from heats h
where h.race_id = 189 and
h.last_updated = (select max(h2.last_updated)
from heats
where h2.race_id = h.race_id and h2.heat = h.heat
)
order by heat asc;