selecting rows in the last 5 minutes using unix time stamp

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

Iam trying to figure out whetere data was save to the db in the las 5 minutes.

SELECT COUNT(id), DATE_FORMAT(`timestamp`, '%Y-%m-%d %H:%i') FROM `table` WHERE `timestamp` >= CURRENT_TIMESTAMP - INTERVAL 5 MINUTE 

timestamp is a unix timestamp (millisecs from 1970).

doesn't work, I get nullnum_rows instead of 0 and if I use

if (!isset($resultHistory->num_rows) || !$resultHistory->num_rows) 

to do actions, the code does not enter the loop..

I also tried

SELECT COUNT(id), DATE_FORMAT(`timestamp`, '%Y-%m-%d %H:%i')     FROM `table`     WHERE DATE_FORMAT(`timestamp`, '%Y-%m-%d %H:%i') >= CURRENT_TIMESTAMP - INTERVAL 5 MINUTE 

回答1:

Current_timestamp returns the current date as a SQL TIMESTAMP, not a UNIX timestamp, so you'd have to convert using the unix_timestamp function:

SELECT COUNT(id), from_unixtime(`timestamp` / 1000, '%Y-%m-%d %H:%i') FROM `table` WHERE `timestamp` >= unix_timestamp(CURRENT_TIMESTAMP - INTERVAL 5 MINUTE) * 1000 

EDIT:

As your timestamp column contains unix time, you're also going to have to use from_unixtime to format the date.

EDIT2:

In MySQL UNIX time is the number of seconds since epoch (1/1/70), so if your timestamp column contains the number of milliseconds, you'll have to divide by 1000 as well.



回答2:

You could do like that :

SELECT COUNT(id), DATE_FORMAT(`timestamp`, '%Y-%m-%d %H:%i') FROM `table` WHERE `timestamp` BETWEEN (DATE_SUB(NOW(),INTERVAL 5 MINUTE)) AND NOW() 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!