删除 MySQL 中 5 天前的数据


若要删除所有 5 天前的数据,则可以使用以下语法 -

delete from yourTableName
   where datediff(now(), yourTableName.yourDateColumnName) > 5;

注意: - 假设当前日期是 2019-03-10。

为理解此概念,让我们创建一个表。创建表的查询如下 -

mysql> create table deleteRowsOlderThan5Demo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Post_Date date
   -> );
Query OK, 0 rows affected (0.69 sec)

对表中插入一些记录。查询如下 -

mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Larry','2019-03-
11');
Query OK, 1 row affected (0.12 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Mike','2019-02-
12');
Query OK, 1 row affected (0.17 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Sam','2019-03-
10');
Query OK, 1 row affected (0.12 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Carol','2019-03-
01');
Query OK, 1 row affected (0.23 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('David','2019-01-
31');
Query OK, 1 row affected (0.19 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('Maxwell','2019-01-
26');
Query OK, 1 row affected (0.10 sec)
mysql> insert into deleteRowsOlderThan5Demo(Name,Post_Date) values('John','2019-02-
19');
Query OK, 1 row affected (0.12 sec)

对表中所有记录进行显示。查询如下 -

mysql> select *from deleteRowsOlderThan5Demo;

输出如下 -

+----+---------+------------+
| Id | Name    | Post_Date  |
+----+---------+------------+
| 1  | Larry   | 2019-03-11 |
| 2  | Mike    | 2019-02-12 |
| 3  | Sam     | 2019-03-10 |
| 4  | Carol   | 2019-03-01 |
| 5  | David   | 2019-01-31 |
| 6  | Maxwell | 2019-01-26 |
| 7  | John    | 2019-02-19 |
+----+---------+------------+
7 rows in set (0.00 sec)

删除所有 5 天前数据命令如下 -

mysql> delete from deleteRowsOlderThan5Demo
   -> where datediff(now(), deleteRowsOlderThan5Demo.Post_Date) > 5;
Query OK, 5 rows affected (0.14 sec)

我们再次查看表记录。查询如下 -

mysql> select *from deleteRowsOlderThan5Demo;

输出如下 -

+----+-------+------------+
| Id | Name  | Post_Date  |
+----+-------+------------+
| 1  | Larry | 2019-03-11 |
| 3  | Sam   | 2019-03-10 |
+----+-------+------------+
2 rows in set (0.00 sec)

更新于:2019-07-30

1 千次以上浏览

开启您的 职业生涯

完成课程后获取认证

开始吧
广告