SQL比较微缩后的两个日期

时间:2015-05-06 14:54:34

标签: mysql sql

我有以下查询。其目的是找出订购产品的时间,检查它们是否符合当天的条件,然后提供清单。

AND ( 
    (NameType <> 'Salad' AND completeDate < DATE_FORMAT( NOW( ) , '%Y-%m-%d' ' 10:30:00' ) ) 
    OR 
    (NameType = 'Salad' AND ( 
        ( DATE_FORMAT( completeDate , '%h:%i:%s' ) <= '14:00:00' ) 
            AND DATE_ADD(DATE_FORMAT(completeDate,'%Y-(%m)-%d'), INTERVAL +1 DAY) < DATE_FORMAT(NOW(),'%Y-%m-%d')
        )
    )
    OR
    (NameType = 'Salad' AND ( 
        ( DATE_FORMAT( completeDate , '%h:%i:%s' ) > '14:00:00' )   
            AND DATE_ADD(DATE_FORMAT(completeDate,'%Y-(%m)-%d'), INTERVAL +2 DAY) < DATE_FORMAT(NOW(),'%Y-%m-%d')
        )
    )
)

逻辑:

If a Bagel is ordered before 10:30 it will arrive that day. If not it will arrive the next.

If a Salad is ordered before 14:00 it will arrive the next day. If after this, it will arrive in two working days.(是的,我觉得我很疯狂!)

因此,当前日期为2015-05-06

这样一张桌子;

 |ID|NameType|  completeDate     |
 |1 |Salad   |2015-05-05 13:00:00|
 |2 |Salad   |2015-05-04 19:00:00|
 |3 |Bagel   |2015-05-05 08:00:00|
 |4 |Bagel   |2015-05-05 11:00:00|

应该输出,

 |ID|NameType|  completeDate     |
 |1 |Salad   |2015-05-05 13:00:00|
 |3 |Bagel   |2015-05-05 08:00:00|

然而它省略了沙拉/ ID 1!

这是如何与日期比较的一些东西吗?想知道是否将它们转换为字符串可能有所帮助。

2 个答案:

答案 0 :(得分:1)

你在'%h:%i:%s'使用了24小时的军事时间,但在'01:30:00'中使用了%h的12小时常规时间(因此下午1:30将显示为'%H:%i:%s' )。这样的格式化可能会有所帮助:

{{1}}

答案 1 :(得分:0)

问题与我如何比较两个字符串有关。

将它们转换为DATE解决了这个问题。

AND ( 
    (NameType <> 'Salad' AND completeDate < DATE_FORMAT( NOW( ) , '%Y-%m-%d' ' 10:30:00' ) ) 
    OR 
    (NameType = 'Salad' AND ( 
        ( DATE_FORMAT( completeDate , '%H:%i:%s' ) <= '14:00:00' ) 
            AND CAST(DATE_ADD(DATE_FORMAT(completeDate,'%Y-(%m)-%d'), INTERVAL +1 DAY) AS DATE) <= CAST(DATE_FORMAT(NOW(),'%Y-%m-%d') AS DATE)
        )
    )
    OR
    (NameType = 'Salad' AND ( 
        ( DATE_FORMAT( completeDate , '%H:%i:%s' ) > '14:00:00' )   
            AND CAST(DATE_ADD(DATE_FORMAT(completeDate,'%Y-(%m)-%d'), INTERVAL +2 DAY) AS DATE) <= CAST(DATE_FORMAT(NOW(),'%Y-%m-%d') AS DATE)
        )
    )
)