我想在mysql中创建一个表,该表有3列user_id,activity - online或offline - 和timestamp, 现在我希望该表显示所有user_id以及最新状态。目前正在使用
SELECT DISTINCT user_id,activity FROM activity ORDER BY timestamp DESC
语句显示用户上次上线和离线的时间,这不是我想要的。
答案 0 :(得分:1)
select user_id, max(timestamp) ts from activity a
inner join
(select user_id, activity, max(timestamp) ts
group by user_id, activity) iam
on iam.user_id =a.user_id and a.ts = iam.ts
答案 1 :(得分:1)
试试这个:
select act.*
from activity as act
inner join (
select user_id, max(timestamp) as max_ts
from activity
group by user_id) as a on act.user_id=a.user_Id and act.timestamp=a.max_ts
这将返回每个用户的最新记录。