9

I have a datetime field in my MySql table where the date and time are recorded in the following format:

2010-12-17 18:06:59

I would like to select records where the datetime is in the last 15 minutes. How do I construct my query to do this?

I tried the following but it doesn't work:

// check in last 15 minutes
$time_duration = (15 * 60);

"SELECT COUNT(CounterId) AS Count FROM visitors_counter WHERE TimeStamp > NOW() - $time_duration"

Thanks!

2 Answers 2

11

You could just do the entire thing in MySQL:

SELECT COUNT(CounterId) AS Count 
FROM visitors_counter
WHERE TimeStamp > (NOW() - INTERVAL 15 MINUTE)
Sign up to request clarification or add additional context in comments.

2 Comments

Little typo : it's MINUTE, not MINUTES
@Vincent -- thanks, was just reviewing the docs to check, edited.
3

You have to subtract an interval :

SELECT COUNT(*) AS Count
FROM visitors_counter
WHERE TimeStamp > NOW() - INTERVAL 15 MINUTE;

I replaced COUNT(CounterId) with COUNT(*) because the latter is faster if CounterId can't be null. If it can, just replace * with CounterId.

P.S. I don't consider timestamp a good column name because it's a key word. Sure, it works correctly, but it may be "better" to replace it with something else.

1 Comment

Thank you! INTERVAL is what I didn't know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.