mysqlsqldatabase-designtriggersmysql-error-1442

MySql Triggers to delete child records in the same table


I have a table that stores parent and child records in it.

I was trying to create a trigger that would delete all child records when the parent is deleted:

Delete From tbl Where ParentId = OLD.Id

While I can save the trigger successfully, when deleting I get this error:

ERROR 1442: Can’t update table ‘tbl′ in stored function/trigger because it is already used by statement which invoked this

What am I doing wrong?


Solution

  • It appears that this is not possible:

    You cannot DELETE rows in the table that activated trigger.

    Some other options you might think about:

    1. Write application logic that deletes the parent and child rows, and call this application logic whenever you want to delete a parent record, instead of deleting it directly.
    2. Cascade delete relationship on the same table, which appears to be possible.
    3. A cleanup process that routinely clears out orphaned child records.
    4. (suggested by @Chris) Separate out the child records from the parent records by adding another table.