How do I query between two dates using MySQL?

前端 未结 10 2417
滥情空心
滥情空心 2020-11-22 00:58

The following query:

SELECT * FROM `objects` 
WHERE (date_field BETWEEN \'2010-09-29 10:15:55\' AND \'2010-01-30 14:15:55\')

returns nothin

10条回答
  •  野性不改
    2020-11-22 01:50

    As extension to the answer from @sabin and a hint if one wants to compare the date part only (without the time):

    If the field to compare is from type datetime and only dates are specified for comparison, then these dates are internally converted to datetime values. This means that the following query

    SELECT * FROM `objects` WHERE (date_time_field BETWEEN '2010-01-30' AND '2010-09-29')
    

    will be converted to

    SELECT * FROM `objects` WHERE (date_time_field BETWEEN '2010-01-30 00:00:00' AND '2010-09-29 00:00:00')
    

    internally.

    This in turn leads to a result that does not include the objects from 2010-09-29 with a time value greater than 00:00:00!

    Thus, if all objects with date 2010-09-29 should be included too, the field to compare has to be converted to a date:

    SELECT * FROM `objects` WHERE (DATE(date_time_field) BETWEEN '2010-01-30' AND '2010-09-29')
    

提交回复
热议问题