仅更改日期,而忽略MySQL中的时间记录

要仅更改日期而不是时间,请使用MySQL INTERVAL和YEAR。由于我们将更新记录,因此,请使用UPDATE并使用INTERVAL设置新值。

让我们看一个例子并创建一个表-

mysql> create table DemoTable
(
   DueDate datetime
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values('2017-08-12 10 :30 :45');
mysql> insert into DemoTable values('2015-09-21 12 :00 :00');
mysql> insert into DemoTable values('2018-12-31 11 :45 :56');
mysql> insert into DemoTable values('2016-01-02 01 :23 :04');

使用select语句显示表中的所有记录-

mysql> select *from DemoTable;

这将产生以下输出-

+-----------------------+
| DueDate               |
+-----------------------+
| 2017-08-12 10 :30 :45 |
| 2015-09-21 12 :00 :00 |
| 2018-12-31 11 :45 :56 |
| 2016-01-02 01 :23 :04 |
+-----------------------+
4 rows in set (0.00 sec)

以下是更改所有日期但不更改时间值的查询-

mysql> update DemoTable
   set DueDate=DueDate+interval 1 year;
Rows matched : 4 Changed : 4 Warnings : 0

让我们再次检查表记录-

mysql> select *from DemoTable;

这将产生以下输出-

+-----------------------+
| DueDate               |
+-----------------------+
| 2018-08-12 10 :30 :45 |
| 2016-09-21 12 :00 :00 |
| 2019-12-31 11 :45 :56 |
| 2017-01-02 01 :23 :04 |
+-----------------------+
4 rows in set (0.00 sec)