如何将当前时间与其他现有的4个时间字段进行比较

时间:2015-03-18 10:44:13

标签: mysql

我有一个包含4个时序的表,如bus_start_time1,bus_end_time1,start_time_2和end_time2。 现在我的要求是在与当前时间进行比较时构建一个介于start_time1和end_time1或start_time2和end_time2之间的查询。

这是我的表:

+------------+-------------+-----------+-------------+-----------+
| vendor_id  | start_time1 | end_time1 | start_time2 | end_time2 |
+------------+-------------+-----------+-------------+-----------+
| 5000788324 | 09:00 AM    | 11:00 AM  | 02:00 PM    | 06:00 PM  | 
| 5000815782 | 10:00 AM    | 01:00 PM  | 02:00 PM    | 10:00 PM  | 
| 5000482136 | 09:00 AM    | 01:00 PM  | 02:00 PM    | 09:00 PM  | 
| 6786788131 | 09:00 AM    | 11:00 AM  | 02:00 PM    | 06:00 PM  | 
+------------+-------------+-----------+-------------+-----------+

我尝试了以下查询,但它对我没有用处:

select count(ven_availability_id) as count from vendor_del_avilability vda where vda.vendor_id = ? and ((vda.bus_start_time1 >  DATE_FORMAT(now(), '%T')  and vda.bus_end_time1 >  DATE_FORMAT(now(), '%T')) or  (vda.bus_start_time2 >  DATE_FORMAT(now(), '%T')  and vda.bus_end_time2 >  DATE_FORMAT(now(), '%T')));

请帮帮我。提前谢谢。

4 个答案:

答案 0 :(得分:0)

介于两者之间:

select f_name, l_name, age from
    -> employee_data where age BETWEEN
    -> 32 AND 40;

理论上没有日期部分,它应该只看到1900年1月1日,所以公平。

答案 1 :(得分:0)

我想,这就是你所需要的:

   select count(*)
   from vendor_del_availability
   where (CURTIME() BETWEEN start_time1 AND end_time1) 
   or (CURTIME() BETWEEN start_time2 AND end_time2);

答案 2 :(得分:0)

假设您的值存储为time值,您可以执行以下操作:

where vda.vendor_id = ? and
      ((vda.bus_start_time1 < time(now())  and
        vda.bus_end_time1 > time(now())
       ) or
       (vda.bus_start_time2 < time(now())  and
        vda.bus_end_time2 > time(now())
       )
      )

如果它们存储为字符串,请使用str_to_date()将其转换为time。您无法在包含AMPM的时间进行字符串比较。

请注意,您的原始查询的开始时间逻辑是向后的。

答案 3 :(得分:0)

试试这个:

SELECT count(vendor_id) as count
FROM vendor_del_avilability
WHERE vendor_id = ?
AND (
    NOW() BETWEEN
    (STR_TO_DATE(CONCAT(CURDATE(), ' ', start_time1), '%Y-%m-%d %h:%i%p'))
    AND 
    (STR_TO_DATE(CONCAT(CURDATE(), ' ', end_time1), '%Y-%m-%d %h:%i%p'))
)
OR
(
    NOW() BETWEEN
    (STR_TO_DATE(CONCAT(CURDATE(), ' ', start_time2), '%Y-%m-%d %h:%i%p')) 
    AND
    (STR_TO_DATE(CONCAT(CURDATE(), ' ', end_time2), '%Y-%m-%d %h:%i%p'))
);