状态 1 表示登录,状态 0 表示注销。如何找到到目前为止登录的用户?
这是表格
user_id time status
57 2015-10-21 09:00:00 1
57 2015-10-21 10:00:00 0
60 2015-10-21 12:30:00 1
55 2015-10-11 08:00:00 1
54 2015-10-21 09:00:00 1
54 2015-10-21 09:15:00 0
50 2015-10-21 08:15:00 1
49 2015-10-21 11:00:00 1
49 2015-10-21 11:00:00 0
预期结果:
user_id status
55 1
60 1
55 1
50 1
最佳答案
您希望用户的最新状态为 0
。
这是一种方法:
select t.*
from thetable t
where t.status = 1 and
not exists (select 1
from thetable t2
where t2.user_id = t.user_id and
t2.status = 0 and
t2.time > t.time
);
这可以利用两个索引:thetable(status, user_id)
和 thetable(user_id, status, time)
。
关于mysql - 如何在mysql中查找已登录但未注销且今天仍然登录的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33321733/