mysql - 如何在mysql中查找已登录但未注销且今天仍然登录的用户?

标签 mysql sql datetime

状态 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/

相关文章:

mysql - 如何在 Mac OS Sierra 上安装 MySQL 5.7.x

php - 我无法在数组中放入值?

2个表中名称列之间的SQL差异函数

python - Arrow 中的时间戳之间的差异

php - 使用MySql从逗号分隔的字符串中提取行

mysql - 如何从数据库中取出数据 "disappear"? MySQL

mysql - 使用 SQL View 和两个用例

sql - 在 SSRS 查询中使用参数

python - 在程序上下文中向日期时间输入添加异常处理的最简单方法是什么?

sql - 如何在SQL Server中将nvarchar类型转换为仅时间类型格式