0

我使用以下内容选择用户添加的最后一个事件

SELECT MAX(user_event_id) from user_events where user_id = 63

event_title如果我尝试,在这一行还有一列:

SELECT MAX(user_event_id), event_title from user_events where user_id = 63

返回的 event_title 与 user_event_id 不对应

是否可以返回最后一个 user_event_id 和 event_title?

4

2 回答 2

4

此解决方案不需要 ORDER BY,如果表很长,它会运行缓慢。

SELECT user_event_id, event_title
FROM user_events
WHERE user_event_id = (SELECT MAX(user_event_id)
                       FROM user_events
                       WHERE user_id = 63)
AND user_id = 63   -- This clause not needed if user_event_id is unique
于 2012-12-16T18:45:54.483 回答
2
SELECT user_event_id, event_title 
from user_events 
where user_id = 63
order by user_event_id desc
limit 1

Most DBMS does not allow to include event_title into field list (like author did) because it is not used for grouping and not aggregate function. But mysql does, often with unexpected result.

UPDATE: This query returns only one record if there are several records with the same min user_event_id for the user. So it addresses slightly different problem, than solution of Barry Brown - which return all records with equal user_event_id.

于 2012-12-16T18:40:10.610 回答