如何在mysql中找到一个带有“wall time”的表的时间范围

时间:2011-06-25 06:27:09

标签: php mysql

我有一个时间字符串,如上午8:00,上午9:00等存储在mysql表中。我想检查时间范围,如果时间是在上午9:00到下午6:00之间的时间上午11:00?如何在mysql中找到它。

时间存储如下

day         depart_time     return_time
Monday      9:00am          5:00pm
Wednesday   9:30am          4:30pm
Tuesday     9:00am          3:00pm

3 个答案:

答案 0 :(得分:3)

您可以使用STR_TO_DATE将字符串数据类型转换为时间。在下面的示例中,将返回“11:00 am”在出发时间和返回时间之间的所有行。

SELECT `depart_time`,
       `return_time`
FROM   `table`
WHERE  STR_TO_DATE('11:00am', '%l:%i%p') BETWEEN STR_TO_DATE(`depart_time`, '%l:%i%p') AND STR_TO_DATE(`return_time`, '%l:%i%p')

STR_TO_DATE函数根据指定的格式解析字符串。在这种情况下,它是:

  • %l:小时(1-12)
  • %i:分钟(00-59)
  • %p:AM / PM

答案 1 :(得分:1)

SELECT depart_time, return_time FROM SCHEDULE
WHERE CASE
WHEN STR_TO_DATE(depart_time, '%l:%i%p') < STR_TO_DATE(return_time, '%l:%i%p') THEN
    STR_TO_DATE(depart_time, '%l:%i%p') <= @check_time AND @check_time < STR_TO_DATE(return_time, '%l:%i%p')
ELSE
    NOT(STR_TO_DATE(return_time, '%l:%i%p') <= @check_time AND @check_time < STR_TO_DATE(depart_time, '%l:%i%p'))
END

用您要检查的时间替换@check_time。此查询将跨越两天的时间。

样本数据:

depart_time return_time
9:00am      5:00pm
11:00pm     1:00am

示例输出:

#SET @check_time = STR_TO_DATE('8:59am', '%l:%i%p');
(no result)

#SET @check_time = STR_TO_DATE('9:00am', '%l:%i%p');
9:00am      5:00pm

#SET @check_time = STR_TO_DATE('11:00am', '%l:%i%p');
9:00am      5:00pm

#SET @check_time = STR_TO_DATE('4:59pm', '%l:%i%p');
9:00am      5:00pm

#SET @check_time = STR_TO_DATE('5:00pm', '%l:%i%p');
(no result)

#SET @check_time = STR_TO_DATE('10:59pm', '%l:%i%p');
(no result)

#SET @check_time = STR_TO_DATE('11:00pm', '%l:%i%p');
11:00pm     1:00am

#SET @check_time = STR_TO_DATE('12:00am', '%l:%i%p');
11:00pm     1:00am

#SET @check_time = STR_TO_DATE('12:59am', '%l:%i%p');
11:00pm     1:00am

#SET @check_time = STR_TO_DATE('1:00am', '%l:%i%p');
(no result)

答案 2 :(得分:0)

试试这个。

选择TIMEDIFF('2006-10-31 11:50:31','2006-10-31 11:50:01')

你需要提供24小时格式。

SELECT SUBTIME('01:00:00.999999','02:00:00.999998');