Home > Database > Mysql Tutorial > How does MySQL use addition and subtraction operators for date operations?

How does MySQL use addition and subtraction operators for date operations?

王林
Release: 2023-09-12 17:17:03
forward
1673 people have browsed it

How does MySQL use addition and subtraction operators for date operations?

MySQL can perform date arithmetic using the addition and subtraction operators by adding the INTERVAL keyword to a time unit, date, or datetime.

Example 1

Add 2 days to a specific date.

mysql> Select '2017-05-20' + INTERVAL 2 day;
+-------------------------------+
| '2017-05-20' + INTERVAL 2 day |
+-------------------------------+
| 2017-05-22                    |
+-------------------------------+
1 row in set (0.00 sec)
Copy after login

Example 2

Subtract 2 days from a specific date.

mysql> Select '2017-05-20' - INTERVAL 2 day;
+-------------------------------+
| '2017-05-20' - INTERVAL 2 day |
+-------------------------------+
| 2017-05-18                    |
+-------------------------------+
1 row in set (0.00 sec)
Copy after login

Example 3

Add 2 hours of time.

mysql> Select '2017-05-20 05:04:35' + INTERVAL 3 hour;
+-----------------------------------------+
| '2017-05-20 05:04:35' + INTERVAL 3 hour |
+-----------------------------------------+
| 2017-05-20 08:04:35                     |
+-----------------------------------------+
1 row in set (0.00 sec)
Copy after login

Example 4

Add one month to a specific date

mysql> Select '2017-05-20 05:04:35' + INTERVAL 1 month;
+------------------------------------------+
| '2017-05-20 05:04:35' + INTERVAL 1 month |
+------------------------------------------+
| 2017-06-20 05:04:35                      |
+------------------------------------------+
1 row in set (0.00 sec)
Copy after login

In this way, with the INTERVAL keyword, we can perform date operations.

The above is the detailed content of How does MySQL use addition and subtraction operators for date operations?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template