MySQL - 将日期年份从 2020 年更改为 2011 年?
mysqlmysqli database
您可以使用 SUBDATE() 将日期年份从 2020 年更改为 2011 年,间隔为 9 年,因为 2020 年和 2011 年之间相差 9 年。
语法如下:
UPDATE yourTableName SET yourDateColumnName=SUBDATE(yourDateColumnName,INTERVAL 9 YEAR);
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table ChangeYearFrom2020To2011 -> ( -> Id int NOT NULL AUTO_INCREMENT, -> ExpiryDate date, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.67 sec)
使用 insert 命令在表中插入一些记录。插入记录的查询如下:
mysql> insert into ChangeYearFrom2020To2011(ExpiryDate) values('2020-09-12'); Query OK, 1 row affected (0.19 sec) mysql> insert into ChangeYearFrom2020To2011(ExpiryDate) values('2020-12-21'); Query OK, 1 row affected (0.17 sec) mysql> insert into ChangeYearFrom2020To2011(ExpiryDate) values('2020-01-29'); Query OK, 1 row affected (0.12 sec) mysql> insert into ChangeYearFrom2020To2011(ExpiryDate) values('2020-06-30'); Query OK, 1 row affected (0.19 sec) mysql> insert into ChangeYearFrom2020To2011(ExpiryDate) values('2020-12-31'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录。查询如下:
mysql> select *from ChangeYearFrom2020To2011;
输出结果如下:
+----+------------+ | Id | ExpiryDate | +----+------------+ | 1 | 2020-09-12 | | 2 | 2020-12-21 | | 3 | 2020-01-29 | | 4 | 2020-06-30 | | 5 | 2020-12-31 | +----+------------+ 5 rows in set (0.00 sec)
以下是仅将年份从 2020 年更改为 2011 年的查询:
mysql> update ChangeYearFrom2020To2011 -> set ExpiryDate=subdate(ExpiryDate,interval 9 year); Query OK, 5 rows affected (0.20 sec) Rows matched: 5 Changed: 5 Warnings: 0
现在我们将再次检查表的所有记录。查询如下:
mysql> select *from ChangeYearFrom2020To2011;
输出结果如下:
+----+------------+ | Id | ExpiryDate | +----+------------+ | 1 | 2011-09-12 | | 2 | 2011-12-21 | | 3 | 2011-01-29 | | 4 | 2011-06-30 | | 5 | 2011-12-31 | +----+------------+ 5 rows in set (0.00 sec)