How to Add Time to Current Timestamp in MySQL?
When working with temporal data in MySQL, it's often necessary to perform calculations involving time manipulation. One such operation is adding a specific duration to the current timestamp.
Consider the example of fetching courses from a courses table where the start time is greater than the current time plus 2 hours. The following query attempts to achieve this:
SELECT * FROM courses WHERE (now() + 2 hours) > start_time;
However, this query syntax is incorrect. To correctly add 2 hours to the current timestamp in MySQL, use the DATE_ADD() function:
SELECT * FROM courses WHERE DATE_ADD(NOW(), INTERVAL 2 HOUR) > start_time;
The DATE_ADD() function takes the current timestamp (NOW()), adds an interval of 2 hours (INTERVAL 2 HOUR), and compares the result with the start_time field of the courses table.
By using the correct syntax, you can effectively retrieve courses that start more than 2 hours from now.
The above is the detailed content of How to Correctly Add Time to the Current Timestamp in MySQL?. For more information, please follow other related articles on the PHP Chinese website!