在 MySQL 表中为某个值添加 30 天?

mysqlmysqli database

要为表中某个值添加 30 天,可以使用 ADDDATE() 函数和 UPDATE 命令。语法如下:

UPDATE yourTableName
SET yourDateColumnName=ADDDATE(yourDateColumnName,INTERVAL 30 DAY);

为了理解上述语法,让我们创建一个表。创建表的查询如下:

mysql> create table Add30DayDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> ShippingDate date,
   -> PRIMARY KEY(ID)
   -> );
Query OK, 0 rows affected (0.76 sec)

使用插入命令在表中插入一些记录。查询如下:

mysql> insert into Add30DayDemo(ShippingDate) values('2019-02-04');
Query OK, 1 row affected (0.20 sec)
mysql> insert into Add30DayDemo(ShippingDate) values('2018-11-15');
Query OK, 1 row affected (0.18 sec)
mysql> insert into Add30DayDemo(ShippingDate) values('2013-05-18');
Query OK, 1 row affected (0.15 sec)
mysql> insert into Add30DayDemo(ShippingDate) values('2017-08-25');
Query OK, 1 row affected (0.20 sec)
mysql> insert into Add30DayDemo(ShippingDate) values('2016-03-01');
Query OK, 1 row affected (0.12 sec)
mysql> insert into Add30DayDemo(ShippingDate) values('2015-09-03');
Query OK, 1 row affected (0.13 sec)

使用 select 语句显示表中的所有记录。查询如下:

mysql> select *from Add30DayDemo;

输出结果如下:

+----+--------------+
| Id | ShippingDate |
+----+--------------+
|  1 | 2019-02-04   |
|  2 | 2018-11-15   |
|  3 | 2013-05-18   |
|  4 | 2017-08-25   |
|  5 | 2016-03-01   |
|  6 | 2015-09-03   |
+----+--------------+
6 rows in set (0.00 sec)

以下是使用 DATEADD() 在表中添加 30 天值的查询:

mysql> update Add30DayDemo
   -> SET ShippingDate=ADDDATE(ShippingDate,INTERVAL 30 DAY);
Query OK, 6 rows affected (0.44 sec)
Rows matched: 6 Changed: 6 Warnings: 0

现在再次检查表记录。查询如下:

mysql> select *from Add30DayDemo;

以下是更新日期后的输出:

+----+--------------+
| Id | ShippingDate |
+----+--------------+
|  1 | 2019-03-06   |
|  2 | 2018-12-15   |
|  3 | 2013-06-17   |
|  4 | 2017-09-24   |
|  5 | 2016-03-31   |
|  6 | 2015-10-03   |
+----+--------------+
6 rows in set (0.00 sec)


相关文章