Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

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?

like image 250
The Time Avatar asked Feb 01 '26 18:02

The Time


2 Answers

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 ? 
like image 69
Tom Avatar answered Feb 04 '26 12:02

Tom


You can simply use BETWEEN....AND and DATE_ADD:

SELECT route 
from arrivaltimes 
INNER JOIN stops ON arrivaltimes.stop_id=stops.stop_id 
WHERE weekday =  ?
and time_format(arrivaltime,'%H:%i') BETWEEN 
    time_format(DATE_ADD(curtime,INTERVAL -2 MINUTE) ,'%H:%i') AND 
    time_format(DATE_ADD(curtime,INTERVAL 2 MINUTE) ,'%H:%i')
and name LIKE ? 
like image 34
Zohar Peled Avatar answered Feb 04 '26 11:02

Zohar Peled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!