tags:

views:

31

answers:

3

Hi, I keep a record of logins in a table. I have columns for id, ip, date and time. From that record of logins I wanna fetch logins made only in the last hour.

I'm sweaping through the MySQL docs on time and date functions, but I just can't seem to combine them correctly.

Can somebody help me?

A: 

Make use of the DATE_SUB() and Now() functions:

select count(*) as cnt
from  log
where date >= DATE_SUB(NOW(),INTERVAL 1 HOUR); 

Hope it helps you : )

SDReyes
Yes, I did something like that, only with TIMESUB (or SUBTIME?). But does this require that the date-field is a datetime-type?
Michael Grons
Yes using TIMESUB is more appropiate. yes, the first expression has to be a datetime expression. the second one should be a time expression. check this out http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_subtime
SDReyes
A: 

without the specifics, I think Date_Add() would work.. by adding to your where clause an add of NOW negative hours

(or Date_Sub() )

DRapp
A: 

I recommend have one datetime column instead of date and time columns.

Suppose you have a datetime column called last_login:

SELECT id, ip_address, last_login
FROM mytable
WHERE last_login >= DATE_SUB(NOW(), interval 1 hour);
Paul Schreiber