Home  >  Article  >  Database  >  Update MySQL date and add a year?

Update MySQL date and add a year?

WBOY
WBOYforward
2023-09-23 08:53:08724browse

更新 MySQL 日期并增加一年?

You can use MySQL's built-in function date_add(). The syntax is as follows -

UPDATE yourTableName SET
yourDateColumnName=DATE_ADD(yourDateColumnName,interval 1 year);

To understand the above syntax, let us first create a table. The query to create the table is as follows -

mysql> create table UpdateDate
   -> (
   -> Id int,
   -> DueDate datetime
   -> );
Query OK, 0 rows affected (0.76 sec)

Use the insert command to insert some records in the table. The query to insert records is as follows -

mysql> insert into UpdateDate values(1001,'2012-5-21');
Query OK, 1 row affected (0.17 sec)

mysql> insert into UpdateDate values(1002,'2013-8-2');
Query OK, 1 row affected (0.17 sec)

mysql> insert into UpdateDate values(1003,'2014-2-27');
Query OK, 1 row affected (0.10 sec)

mysql> insert into UpdateDate values(1004,'2016-11-1');
Query OK, 1 row affected (0.18 sec)

mysql> insert into UpdateDate values(1005,'2017-12-24');
Query OK, 1 row affected (0.12 sec)

Now let us use the select command to display all the records in the table. The query is as follows -

mysql> select *from UpdateDate;

Output

+------+---------------------+
| Id   | DueDate             |
+------+---------------------+
| 1001 | 2012-05-21 00:00:00 |
| 1002 | 2013-08-02 00:00:00 |
| 1003 | 2014-02-27 00:00:00 |
| 1004 | 2016-11-01 00:00:00 |
| 1005 | 2017-12-24 00:00:00 |
+------+---------------------+
5 rows in set (0.00 sec)

The following query can be used to update the date to 1 year using date_add() and interval. The query is as follows -

mysql> update UpdateDate set DueDate=date_add(DueDate,interval 1 year);
Query OK, 5 rows affected (0.15 sec)
Rows matched: 5 Changed: 5 Warnings: 0

Use the select command to check the table. The query is as follows -

mysql> select *from UpdateDate;

Output

+------+---------------------+
| Id   | DueDate             |
+------+---------------------+
| 1001 | 2013-05-21 00:00:00 |
| 1002 | 2014-08-02 00:00:00 |
| 1003 | 2015-02-27 00:00:00 |
| 1004 | 2017-11-01 00:00:00 |
| 1005 | 2018-12-24 00:00:00 |
+------+---------------------+
5 rows in set (0.00 sec)

Look at the sample output above, all values ​​have been updated. If you want to update a specific date time, use where condition.

The above is the detailed content of Update MySQL date and add a year?. 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