I have table ORDERS where is stored data about orders with their status and the date of order. I would like to search all orders with specified status and which was made yesterday after 3pm untill today 4pm. The query will run in different times (10am, 3pm, 5 pm... regardless).

So on example: if I run the query today (13.05.2014) I would like to get all orders made from 2014-12-05 15:00:00 untill 13-05-2015 16:00:00

The date is stored in format: YYYY-MM-DD HH:MM:SS

What I got is:

select *
from orders
where status = 'new'
and (

    (
    date_add(created_at, INTERVAL 1 day) = CURRENT_DATE() 
    and hour(created_at) >= 15
    ) /*1*/

    or (
    date(created_at) = CURRENT_DATE() 
    and hour(created_at) <= 16
    ) /*2*/
)

And I get only orders made today - like only the 2nd condition was taken into account. I prefer not to use created >= '2014-05-12 16:00:00' (I will not use this query, someone else will).

有帮助吗?

解决方案

When you add an interval of 1 day to the date/time, you still keep the time component. Use date() for the first condition:

where status = 'new' and
      ((date(date_add(created_at, INTERVAL 1 day)) = CURRENT_DATE() and
        hour(created_at) >= 15
       ) /*1*/ or
       (date(created_at) = CURRENT_DATE() and
        hour(created_at) <= 16
       ) /*2*/
      )

And alternative method is:

where status = 'new' and
      (created_at >= date_add(CURRENT_DATE(), interval 15-24 hour) and
       created_at <= date_add(CURRENT_DATE(), interval 16 hour)
      )

The advantage of this approach is that all functions are moved to CURRENT_DATE(). This would allow MYSQL to take advantage of an index on created_at.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top