简体   繁体   中英

How to find users who are logged in but not logged out and is still logged in today in mysql?

The status 1 means Login and Status 0 means Logout. How do I find users who are logged in till now?

Here's the table

 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    

Expected Result :

 user_id            status                          

    55              1       
    60              1          
    55              1          
    50              1  

You want users whose more recent status is 0 .

Here is one method:

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
                 );

This can take advantage of two indexes: thetable(status, user_id) and thetable(user_id, status, time) .

While the query presented so far is the most straightforward on I would like to show an alternative variant:

The number of entries of a user who is not logged in at the moment is alway even (pairs of 1 and 0). If a user is logged in, the number is odd.

Consequently:

select user_id, count(*), sum(status) from tee
group by user_id having count(*)/sum(status) <> 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM