如何使用MySQL更新datetime字段的日期?
借助算术运算符minus(-)更新datetime字段的日期。
语法如下
update yourTableName set yourDateTimeColumnName=yourDateTimeColumnName - interval yourValue day where date(yourDateTimeColumnName)=’yourDateValue’;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table updateDateDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ArrivalDate datetime -> );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into updateDateDemo(ArrivalDate) values('2011-01-13'); mysql> insert into updateDateDemo(ArrivalDate) values('2013-04-21'); mysql> insert into updateDateDemo(ArrivalDate) values('2016-12-22'); mysql> insert into updateDateDemo(ArrivalDate) values('2017-02-25'); mysql> insert into updateDateDemo(ArrivalDate) values('2018-08-19'); mysql> insert into updateDateDemo(ArrivalDate) values('2019-02-27');
使用select语句显示表中的所有记录。
查询如下
mysql> select *from updateDateDemo;
以下是输出
+----+---------------------+ | Id | ArrivalDate | +----+---------------------+ | 1 | 2011-01-13 00:00:00 | | 2 | 2013-04-21 00:00:00 | | 3 | 2016-12-22 00:00:00 | | 4 | 2017-02-25 00:00:00 | | 5 | 2018-08-19 00:00:00 | | 6 | 2019-02-27 00:00:00 | +----+---------------------+ 6 rows in set (0.00 sec)
这是更新日期时间字段的日期的查询
mysql> update updateDateDemo -> set ArrivalDate=ArrivalDate-interval 7 day -> where date(ArrivalDate)='2019-02-27'; Rows matched: 1 Changed: 1 Warnings: 0
现在从表中检查更新的记录
mysql> select *from updateDateDemo;
以下是输出
+----+---------------------+ | Id | ArrivalDate | +----+---------------------+ | 1 | 2011-01-13 00:00:00 | | 2 | 2013-04-21 00:00:00 | | 3 | 2016-12-22 00:00:00 | | 4 | 2017-02-25 00:00:00 | | 5 | 2018-08-19 00:00:00 | | 6 | 2019-02-20 00:00:00 | +----+---------------------+ 6 rows in set (0.00 sec)