简体   繁体   中英

Delete rows older than 30 minutes in MySQL

In my table mytable . I have a column named session_time (float) where I store the time in microseconds when the row was added (I use the PHP function microtime(true) to get a float). How can I delete all rows from my table mytable which are older than 20 minutes?

I already tried something like this:

DELETE FROM mytable WHERE session_time < DATE_SUB(NOW(), INTERVAL 1800 SECOND)

But this deletes all rows!

UPDATED...

Instead of using php microtime(true) , you should use MySQL function NOW(). Delete the old column, and make a new one :

ALTER TABLE your_table ADD session_time DATETIME NOT NULL DEFAULT NOW();

Now when you add a row, it's session_time will be set to the current time automatically, and you do not need to insert any value for session_time.

Now for deleting all rows older than 30 minutes, use :

DELETE FROM your_table WHERE TIMESTAMPDIFF(MINUTE,session_time,NOW()) > 30;

Try

DELETE FROM  myTABLE  WHERE session_time < (now() - interval 30 minute)

I didn't test it. I think it shoud work as well.

PHP microtime() uses unix timestamp format, not the DATETIME format. If you are storing things like that, you could use PHP to fill the query or use MySQL's unix_timestamp() function .

For PHP, it would be as simple as:

$query = 'DELETE FROM mytable WHERE session_time < '.time() - 1800;

I would recommend just using the DATETIME format on session_time though, you should take advantage of MySQL's storage types.

It sounds like you're comparing a microsecond value generated in PHP, to a timestamp value generated in mysql. There's a few things that could go wrong here, since you may not actually be comparing time to time but time to float, or your PHP app is using a different clock than your mysql.

Since you're doing the comparison in SQL, you should save the session_time value based on SQL too. This is a good place for a default value, eg:

mysql> create table mytable ( id int not null, session_time timestamp default now() );

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