1

以表为例:

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;
4

2 回答 2

1

MySQL 可能允许您建议的语法类型 - 指定也不属于 group by 的非聚合列 - 但这是非标准的,恕我直言,这是一个不好的习惯。

相反,你会这样做:

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,则此查询将返回所有所述行。

于 2013-07-17T08:19:08.540 回答
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
于 2013-07-17T08:49:33.390 回答