I want to keep only last 5 records in my table. So I intended to create a trigger (on MyTable) which would after insert of a new record delete all records except last 5 ones. When I try to create this trigger:
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//
I get the following error message: Error Code: 1235. This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
. I use MySQL v5.7.14
If I enclose the IN clause into subquery like this:
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//
I'm able to create such a trigger but now I cannot insert records into my table MyTable
. I get the following error message:
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.
What could be the solution? (I don't want cron job for deleting old records)