Retrieving Data Between Two Dates in MySQL
When dealing with datetime values in MySQL, it's essential to consider the midnight default for short date formats. This can lead to unexpected results when querying data within a date range.
For instance, if you want to select records where the created_at column falls between '2011-12-01' and '2011-12-06,' using the following query:
SELECT `users`.* FROM `users` WHERE created_at >= '2011-12-01' AND created_at <= '2011-12-06'
may not return the desired results. This is because the short date format implicitly interprets times as midnight.
To rectify this issue, adjust the query to use '2011-12-07' as the upper bound:
SELECT `users`.* FROM `users` WHERE created_at >= '2011-12-01' AND created_at <= '2011-12-07'
Alternatively, you can use MySQL's date_add() function or the BETWEEN operator to achieve the same result:
SELECT `users`.* FROM `users` WHERE created_at >= '2011-12-01' AND created_at <= date_add('2011-12-01', INTERVAL 7 DAY)
SELECT `users`.* FROM `users` WHERE created_at BETWEEN '2011-12-01', date_add('2011-12-01', INTERVAL 7 DAY)
By considering the default midnight interpretation of short date formats, you can accurately retrieve data within specified date ranges in MySQL.
The above is the detailed content of How to Correctly Retrieve MySQL Data Within a Specific Date Range?. For more information, please follow other related articles on the PHP Chinese website!