使用时间格式选择+ - 2分钟()

时间:2015-05-20 18:43:41

标签: mysql sql

我试图从到达时间表中选择不到确切的到达时间,但是 - 使用此查询+ 2分钟:

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 ? 

如何选择+ - 2分钟?

2 个答案:

答案 0 :(得分:2)

如果字段到达时间是TIME字段,则应该有效:

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 ? 

或者您可以使用BETWEEN运算符:

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 ? 

答案 1 :(得分:1)

您只需使用BETWEEN....ANDDATE_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 ?