简体   繁体   中英

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') . But that does not seem to work. I also tried sub-queries (first orderBy and then distinct) but also no result.

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:

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

The first second query would just get you the user_id and date whereas the second query would give you everything:

| 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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