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.
The above is the detailed content of How to Efficiently Compare Dates with MySQL DATETIME Fields?. For more information, please follow other related articles on the PHP Chinese website!