简体   繁体   中英

Insert into MySQL table if no row added within 5 minutes

I have a table which contains a column consisting of timestamps. I want to check if there is a new row within 5 minutes period of time. If not, then insert a new row or update the last row status column.

I tried something like this:

UPDATE table
SET status = 'offline'
WHERE CURRENT_TIMESTAMP() > ((SELECT MAX(dateandtime)) + INTERVAL 5 MINUTE)

or insert into ... but no success so far. I'm using PHP in WordPress if that matters.

I hope this helps you. If you want to add new row, you need to use INSERT command with selection like this...

INSERT INTO sessions(user_id, last_visit)
SELECT 1, CURRENT_TIMESTAMP
WHERE EXISTS (
      SELECT 1
      FROM sessions
      WHERE user_id = 1
      HAVING (MAX(last_visit) + INTERVAL 5 MINUTE) < CURRENT_TIMESTAMP
);

If you want to update status column, you need to use simple UPDATE

UPDATE sessions
SET status = 'offline'
WHERE (last_visit + INTERVAL 5 MINUTE) < CURRENT_TIMESTAMP;

Btw, you just need to have a last_visit column, and if it's less than now + 5 min, you already know that the user is offline. And you have to update this value on every authorized request with simple update like.

update users set last_visit = CURRENT_TIMESTAMP where id = ?;

So your User class will be have a function getStatus() like this:

public function getStatus() {
    if ($this->lastVisit < (Carbon::now()->subMinutes(5))) {
        return 'offline';
    }    
    return 'online';
}

Assuming you have an auto-increment primary key, you can do this with replace :

replace into foo (id,dateandtime,status) values (
    (select id from foo f where dateandtime > now()-interval 5 minute order by dateandtime desc limit 1),
    now(),
    # or if you want to preserve the current timestamp, replace the previous now() with:
    #coalesce((select max(dateandtime) from foo f where dateandtime > now()-interval 5 minute), now()),
    'offline'
);

This tries to find the id of the row to update, or uses null to trigger a new auto-increment id to be generated.

Note that replace is unsafe (may cause the source and replica to diverge) when using statement-based replication; in that case you would need a stored procedure, or in your code (in a transaction, to prevent a race condition) to do an update, and only if it updated 0 rows, do an insert.

fiddle fiddle

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