要删除所有30天以上的行,您需要将DELETE与INTERVAL一起使用。使用<now()
即小于运算符可获取当前日期之前的所有记录。
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> UserMessage text, -> UserMessageSentDate date -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Hi','2019-06-01'); mysql> insert into DemoTable values('Hello','2019-07-02'); mysql> insert into DemoTable values('Awesome','2019-05-04'); mysql> insert into DemoTable values('Good','2019-01-10');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
+-------------+---------------------+ | UserMessage | UserMessageSentDate | +-------------+---------------------+ | Hi | 2019-06-01 | | Hello | 2019-07-02 | | Awesome | 2019-05-04 | | Good | 2019-01-10 | +-------------+---------------------+ 4 rows in set (0.00 sec)
以下是删除所有早于30天的行的查询-
mysql> delete from DemoTable where UserMessageSentDate < now() - interval 30 DAY;
让我们再次检查表记录-
mysql> select *from DemoTable;
输出结果
+-------------+---------------------+ | UserMessage | UserMessageSentDate | +-------------+---------------------+ | Hello | 2019-07-02 | +-------------+---------------------+ 1 row in set (0.00 sec)