MySQL Date and DATETIME Comparisons
Comparing date-like strings poses challenges when dealing with fields stored as DATETIME. Consider the database table calendar, where startTime is a DATETIME field. Selecting rows based on a date string, such as "2010-04-29," requires careful handling to match the DATETIME values accordingly.
SOLUTION:
To achieve the desired comparison, utilize the DATE() function:
SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'
The DATE() function extracts the date component from a DATETIME value, effectively stripping away the time information. This ensures that the date string you defined ("2010-04-29") can be directly compared with the date extracted from the startTime DATETIME field.
PERFORMANCE OPTIMIZATION:
The DATE() function can be more efficient than alternative approaches for large tables. For instance, the SALIL solution using STRCMP took 4.48 seconds for a 2 million row table, while the DATE() approach completed in just 2.25 seconds. Consider the DATE() function for optimal performance in such scenarios.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3