简体   繁体   中英

Best way to determine if a user went offline in MySQL

So my script currently forces the user to send a "ping" every 10 minutes. This inserts a record into MySQL with the user ID and the current timestamp.

What I would like to achieve is seeing if any of the users went offline recently. In theory that would be selecting a recently online (20ish minutes ago) user, then checking if there has not been a ping in the past 11 minutes except I don't seem to be able to figure out how. This is what I have so far:

SELECT * FROM status WHERE time > (CURTIME() - 1200) AND time < (CURTIME() - 660)

I have to add, I do this in combination with PHP but that shouldn't really matter.

Any help is appreciated.

There are a lot of ways to do this. Here's one, assuming you have a primary key called id :

SELECT *
FROM status
LEFT JOIN (
    SELECT id
    FROM status
    WHERE time > (CURTIME() - 660)  // was on within last 5 minutes
) sub ON
    sub.id = status.id
WHERE
    time > (CURTIME() - 1200)  // was on within last 20 minutes
    AND sub.id IS NULL;        // was on within last 20, but not last 5

I would try something like that :

SELECT TIMEDIFF(CURTIME(), MAX(s.time)) AS duration, s.user
FROM status s
GROUP BY s.user
HAVING duration > 660 AND duration < 1200;

If the username is not stored in the status table. You should perform a JOIN between Status and User.

You can use a BETWEEN statement if you want to check duration for a specific range too.

EDIT : Thanks to Madbreaks about the "recently" constraint. You can add a AND duration < xxxx to do not retrieve old durations and keep only "recent" status in your result set.

Use between for that:

SELECT *
FROM `status`
WHERE (`time` BETWEEN (CURTIME() - 660) AND (CURTIME() - 1200))

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