Mysql – Deleting old rows when a new one is added and there are more than 100 rows

MySQLtrigger

For a school assignment we need to keep the number of rows in a mysqldb under 100. The newest rows must stay. I've tried using a trigger but with no success.

CREATE TRIGGER delete_rows 
AFTER INSERT ON `check`.log 
FOR EACH ROW 
BEGIN 
   IF(SELECT COUNT(*) FROM `check`.log)>100 
   THEN 
      DELETE FROM `check`.log LIMIT 1; 
   END IF; 
END

This resulted in the following error:

ERROR 1442 (HY000): Can't update table 'log' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Then I tried monitoring /var/lib/mysql/check/log.ibd with incron and let it execute a script. when opening log.ibd with nano, incron executes my script but when I use mysql to insert something into it, nothing happens.

The incron instruction:

/var/lib/mysql/check/log.ibd IN_ALL_EVENTS /etc/scripts/test

can somebody please help me.

Best Answer

Your trigger is not specifying which row to delete and is only limiting it to deleting a single record. You are going to want to update the trigger to specify which record to delete and I would guess that you want to delete the oldest one.

https://dev.mysql.com/doc/refman/5.6/en/delete.html

The LIMIT clause places a limit on the number of rows that can be deleted