表格例如:
event_id| group_id | updated_at
1 | 1 |2012-01-02
2 | 1 |2012-01-01
3 | 2 |2012-01-01
4 | 2 |2012-01-02
5 | 3 |2012-01-01
我需要选择所有具有最大日期的event_id,按group_id分组。所以正确的结果将是:
event_id| group_id | updated_at
1 | 1 |2012-01-02
4 | 2 |2012-01-02
5 | 3 |2012-01-01
我可以从选择MAX(updated_at)的同一行中选择event_id吗?
SELECT event_id, group_id, MAX(updated_at)
FROM my_table
GROUP BY group_id;
答案 0 :(得分:1)
MySQL可能允许您建议的语法类型 - 指定非聚合列也不属于该组 - 但它是非标准的,恕我直言是一个坏习惯。
相反,你会这样做:
SELECT t1.event_id, t1.group_id, t1.updated_at
FROM my_table t1
INNER JOIN
(
SELECT group_id, MAX(updated_at) AS max_updated_at
FROM my_table
GROUP BY group_id
) t2 ON t1.group_id = t2.group_id AND t1.updated_at = t2.max_updated_at
请注意,如果updated_at
对于给定的group_id
而言不是唯一的,则此查询将返回所有所述行。
答案 1 :(得分:1)
与lc的解决方案类似,以下内容允许您获取最近一天的记录,然后获取那些记录中每天event_id最高的记录: -
SELECT t1.event_id, t1.group_id, t1.updated_at
FROM my_table t1
INNER JOIN
(
SELECT group_id, MAX(updated_at) AS max_updated_at
FROM my_table
GROUP BY group_id
) t2
ON t1.group_id = t2.group_id AND t1.updated_at = t2.max_updated_at
INNER JOIN
(
SELECT group_id, updated_at, MAX(event_id) AS max_event_id
FROM my_table
GROUP BY group_id, updated_at
) t3
ON t1.group_id = t3.group_id
AND t1.event_id = t2.max_event_id
AND t3.max_updated_at = t3.updated_at