[英]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.