如何将当前时间和日期与数据库中的现有时间字段和日期进行比较?

时间:2015-03-24 13:35:32

标签: mysql

我有一个表,其中包含start_time,end_time和date字段作为字符串。

表:

+------------+-------------+-----------+---------------+
| vendor_id  | start_time  | end_time  | date          |
+------------+-------------+-----------+---------------+
| 5000788324 | 09:00 AM    | 11:00 AM  | 17-03-2015    |
| 5000815782 | 10:00 AM    | 01:00 PM  | 17-03-2015    | 
| 5000482136 | 09:00 AM    | 01:00 PM  | 17-03-2015    |
| 6786788131 | 09:00 AM    | 11:00 AM  | 17-03-2015    | 
+------------+-------------+-----------+---------------+

现在我的要求是在与当前时间和日期进行比较时构建一个介于date,start_time和end_time之间的查询。

我试过了:

SELECT end_time, NOW() FROM vendor_no_del_time vda WHERE vda.vendor_id = "5000482136" AND (
    NOW() BETWEEN
    (STR_TO_DATE(CONCAT(CURDATE(), ' ', vda.start_time), '%Y-%m-%d %h:%i%p'))
    AND 
    (STR_TO_DATE(CONCAT(CURDATE(), ' ', vda.end_time), '%Y-%m-%d %h:%i%p'))
);

但没用。请帮帮我

1 个答案:

答案 0 :(得分:1)

使用正确的数据格式,并在表达式中包含date

SELECT end_time, NOW()
FROM vendor_no_del_time vda
WHERE vda.vendor_id = 5000482136 AND (
    NOW() BETWEEN STR_TO_DATE(CONCAT(date, ' ', vda.start_time), '%d-%m-%Y %h:%i%p')) AND
                  STR_TO_DATE(CONCAT(date, ' ', vda.end_time), '%d-%m-%Y %h:%i%p')
);