The Time The Time - 3 months ago 21
MySQL Question

Select +- 2 minutes with the time-format()

I am trying to select not the exactly arrivaltime from my arrivaltimes table but -+ 2 minutes with this query:

SELECT route from arrivaltimes INNER JOIN stops
ON arrivaltimes.stop_id=stops.stop_id
WHERE weekday = ?
and time_format(arrivaltime,'%H:%i')= time_format(curtime() ,'%H:%i')
and name LIKE ?


How can I select +- 2 minutes?

Tom Tom
Answer

If the field arrivaltime is a TIME field, this should work:

SELECT route
FROM arrivaltimes
INNER JOIN stops ON (arrivaltimes.stop_id = stops.stop_id)
WHERE
    weekday =  ?
    AND arrivaltime >= curtime() - INTERVAL 2 MINUTE
    AND arrivaltime <= curtime() + INTERVAL 2 MINUTE
    AND name LIKE ? 

Or you can use the BETWEEN operator:

SELECT route
FROM arrivaltimes
INNER JOIN stops ON (arrivaltimes.stop_id = stops.stop_id) 
WHERE
    weekday =  ?
    AND arrivaltime BETWEEN curtime() - INTERVAL 2 MINUTE AND curtime() + INTERVAL 2 MINUTE
    AND name LIKE ?