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

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

王林
王林 forward
2023-09-12 17:17:03 1397browse

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)

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)

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)

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)

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete