仅保留最后N条记录的触发器

时间:2018-11-28 10:26:18

标签: mysql triggers

我只想在表中保留最后5条记录。因此,我打算在插入新记录后创建一个触发器(在MyTable上),然后删除除最后5条记录以外的所有记录。当我尝试创建此触发器时:

DELIMITER //
CREATE TRIGGER DeleteOldRecords AFTER INSERT ON MyTable FOR EACH ROW
BEGIN
  DELETE FROM MyTable WHERE id NOT IN
  (SELECT id FROM MyTable ORDER BY id DESC LIMIT 5);
END//

我收到以下错误消息:Error Code: 1235. This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'。我使用MySQL v5.7.14

如果我将IN子句包含在子查询中,如下所示:

DELIMITER //
CREATE TRIGGER DeleteOldRecords AFTER INSERT ON MyTable FOR EACH ROW
BEGIN
  DELETE FROM MyTable WHERE id NOT IN
  (SELECT id FROM (SELECT id FROM MyTable ORDER BY id DESC LIMIT 5) x);
END//

我能够创建这样的触发器,但是现在我无法将记录插入到表MyTable中。我收到以下错误消息:Error Code: 1442. Can't update table 'MyTable' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

有什么解决方案? (我不希望cron作业删除旧记录)

0 个答案:

没有答案