![](/img/trans.png)
[英]MYSQL - Two tables get record from second table last tracked row for each user
[英]Get last row (activity) for each user from a MySQL table
我有一个表,其中包含用户执行的所有活动(登录,帖子,搜索等)的日志。
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
现在,我想获取所有用户及其上次活动日期的列表。 因此,在我的示例中,我想获得:
User 1: 2015-02-18
User 2: 2015-02-17
User 3: 2015-02-17
我的想法是先通过orderBy 'created_at' DESC
,然后执行DISTINCT('user_id')
。 但这似乎不起作用。 我也尝试了子查询(先是orderBy,然后是distinct),但也没有结果。
关于如何解决这个问题的任何想法?
如果您只关心user_id和created_date,则可以按user_id分组并使用max()聚合函数:
select user_id, max(created_at) as last_created_at from your_table group by user_id;
或者,如果您想要最后一行的所有详细信息,则可以在派生表中检索最大值并在联接中使用该最大值:
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;
第一个查询将只为您提供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 |
尝试使用以下查询:
select user_id, max(created_at) as last_activity
from your_table
group by user_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.