如何在MySQL中删除超过14天的行?
要删除,请使用MySQLDELETE。但是,要获取早于14天的记录,请减去日期间隔为14天的当前日期。相同的语法如下所示-
delete from yourTableName where yourColumnName< (curdate() - interval 14 day);
让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, DueDate date );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(DueDate) values('2019-08-20'); mysql> insert into DemoTable(DueDate) values('2019-08-19'); mysql> insert into DemoTable(DueDate) values('2018-08-19'); mysql> insert into DemoTable(DueDate) values('2018-08-18'); mysql> insert into DemoTable(DueDate) values('2019-08-15');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable ;
这将产生以下输出-
+----+------------+ | Id | DueDate | +----+------------+ | 1 | 2019-08-20 | | 2 | 2019-08-19 | | 3 | 2018-08-19 | | 4 | 2018-08-18 | | 5 | 2019-08-15 | +----+------------+ 5 rows in set (0.00 sec)
以下是删除超过14天的行的查询-
mysql> delete from DemoTable where DueDate − (curdate() - interval 14 day);
让我们再次检查表记录-
mysql> select *from DemoTable;
这将产生以下输出。现在,所有超过14天的行都将被删除-
+----+------------+ | Id | DueDate | +----+------------+ | 1 | 2019-08-20 | +----+------------+ 1 row in set (0.00 sec)