comparing dates by month and year in mysql

前端 未结 4 1944
醉话见心
醉话见心 2021-02-13 18:11

I have a table containing data about events and festivals with following columns recording their start and end dates.

  • Start_Date
  • End_Date

d

4条回答
  •  滥情空心
    2021-02-13 18:22

    I don't like either of the other two answers, because they do not let the optimizer use an index on start_date. For that, the functions need to be on the current date side.

    So, I would go for:

    where start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
          start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
    

    All the date functions are on curdate(), which does not affect the ability of MySQL to use an index in this case.

    You can also include the condition on end_date:

    where (start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
           start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
          ) and
          end_date <= date_add(curdate(), interval 30 day)
    

    This can still take advantage of an index.

提交回复
热议问题