MySQL DATE_ADD根据另一列中的值增加日期?
让我们首先创建一个表,其中一个列为DueDate,另一个为“RepeatTime”(重复次数),该表显示了用户提交付款的次数-
mysql> create table DemoTable -> ( -> DueDate date, -> RepeatTime int -> ); Query OK, 0 rows affected (0.57 sec)
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('2019-01-23',3); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('2019-06-22',6); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('2019-03-28',2); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('2017-07-25',6); Query OK, 1 row affected (0.15 sec)
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
这将产生以下输出-
+------------+------------+ | DueDate | RepeatTime | +------------+------------+ | 2019-01-23 | 3 | | 2019-06-22 | 6 | | 2019-03-28 | 2 | | 2017-07-25 | 6 | +------------+------------+ 4 rows in set (0.00 sec)
这是根据另一列中的值递增日期的查询-
mysql> update DemoTable set DueDate=date_add(DueDate,interval RepeatTime MONTH) where RepeatTime!=6; Query OK, 2 rows affected (0.25 sec) Rows matched: 2 Changed: 2 Warnings: 0
让我们再次检查表记录-
mysql> select *from DemoTable;
输出结果
这将产生以下输出-
+------------+------------+ | DueDate | RepeatTime | +------------+------------+ | 2019-04-23 | 3 | | 2019-06-22 | 6 | | 2019-05-28 | 2 | | 2017-07-25 | 6 | +------------+------------+ 4 rows in set (0.00 sec)