tags:

views:

99

answers:

5

Hello,

I have a script that sends out emails every minute. When it starts its loop, it queries the database for all entries that are equal to the current utc time. I would like to have it find all entries in the database that correspond to the current time down to the minute.

So there is a 'time' column that stores the utc time: '2009-03-06 20:18:31'. When it searches is there any way to ignore the seconds attribute with out changing how I store the time?

EDIT: I'm using mysql server.

Thanks!

A: 

I've performed this logic before:

Query for: TimeField >= (Now - 1 Minute).

You could also modify this logic to query for TimeField >= (Now - # of seconds passed in the current minute) - this might more accurately retrieve what you are looking for.

tehblanx
A: 

Make sure you do the calculation on the "now" part of the inequality. In SQL Server you can use DATEADD(mi, -1, GETDATE()). If you perform the function on the column, you'll likely end up generating a RBAR operation.

K. Brian Kelley
A: 
where datediff(minute, Time, getdate()) = 0

This will work on SQL Server, but as you don't specify what server you're using it's hard to tell if it will work for you.

Garry Shutler
SQL Server won't use an index on the time field for this query though.
Tom H.
+3  A: 

In MySQL:

SELECT *
FROM   table
WHERE  time >= NOW() - INTERVAL EXTRACT(SECOND FROM NOW()) SECOND
       AND time < NOW() - INTERVAL (EXTRACT(SECOND FROM NOW()) + 60) SECOND

This will efficiently use an index on time field.

Quassnoi
A: 

this was the actual sql statement that I used. Notice that it was heavy influenced by Quassnoi's response but there are some key differences. I used the UTC_TIMESTAMP instead of NOW().

select * 
from table
where time < UTC_TIMESTAMP() + INTERVAL(1) MINUTE  - INTERVAL (EXTRACT(SECOND FROM UTC_TIMESTAMP())) SECOND 
and time >= UTC_TIMESTAMP() - INTERVAL (EXTRACT(SECOND FROM UTC_TIMESTAMP())) SECOND;
vrish88