简体   繁体   English

从MySQL表获取每个用户的最后一行(活动)

[英]Get last row (activity) for each user from a MySQL table

I have a table with a log of all activities that my users do (logins, posts, searches, ...). 我有一个表,其中包含用户执行的所有活动(登录,帖子,搜索等)的日志。

id   user_id   created_at    activity

1    2         2015-02-14    x
2    3         2015-02-15    x
3    1         2015-02-14    x
4    2         2015-02-16    x
5    2         2015-02-17    x
6    3         2015-02-17    x
7    1         2015-02-17    x
8    1         2015-02-18    x
9    2         2015-02-19    x

Now I want to get a list with all users and the date of their LAST activity. 现在,我想获取所有用户及其上次活动日期的列表。 So in my example I want to get: 因此,在我的示例中,我想获得:

User 1: 2015-02-18
User 2: 2015-02-17
User 3: 2015-02-17

My idea was to first orderBy 'created_at' DESC and then do a DISTINCT('user_id') . 我的想法是先通过orderBy 'created_at' DESC ,然后执行DISTINCT('user_id') But that does not seem to work. 但这似乎不起作用。 I also tried sub-queries (first orderBy and then distinct) but also no result. 我也尝试了子查询(先是orderBy,然后是distinct),但也没有结果。

Any ideas on how to solve this? 关于如何解决这个问题的任何想法?

If you just care about the user_id and created_date you can group by user_id and use the max() aggregate function: 如果您只关心user_id和created_date,则可以按user_id分组并使用max()聚合函数:

select user_id, max(created_at) as last_created_at from your_table group by user_id;

Or if you want all details for the last rows you can retrieve the max values in a derived table and use that in a join: 或者,如果您想要最后一行的所有详细信息,则可以在派生表中检索最大值并在联接中使用该最大值:

select * from your_table t1
join (select user_id, max(created_at) as max_date 
      from table1 group by user_id
     ) t2 on t1.user_id = t2.user_id and t1.created_at = t2.max_date;

Sample SQL Fiddle 示例SQL提琴

The first second query would just get you the user_id and date whereas the second query would give you everything: 第一个查询将只为您提供user_id和日期,而第二个查询将为您提供所有信息:

| id | user_id | created_at | activity | user_id |   max_date |
|----|---------|------------|----------|---------|------------|
|  6 |       3 | 2015-02-17 |        x |       3 | 2015-02-17 |
|  8 |       1 | 2015-02-18 |        x |       1 | 2015-02-18 |
|  9 |       2 | 2015-02-19 |        x |       2 | 2015-02-19 |

Try with this query: 尝试使用以下查询:

select user_id, max(created_at) as last_activity
from your_table
group by user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM