Search code examples
mysqlsqlforeign-keyscascadecascading-deletes

How to CASCADE deletion to children without reference to the parent


Is it possible to apply cascading deletion of child rows on parent deletion to this MySQL schema?

CREATE TABLE parent (
    id INTEGER,
    specialChildrenId INTEGER,
    PRIMARY KEY (id)
)

-- Always 1:1 related to whatever references it
-- (not necessarily referenced by parent)
CREATE TABLE child (
    id INTEGER,
    PRIMARY KEY (id)
)

I cannot put a reference from the child to the parent as in my application a child can be either 1:1 related to a parent or 1:1 related to another completely different table.


Solution

  • You can add a trigger on the two (or more) parent tables to delete child row before delete like so:

    delimiter |
    
    CREATE TRIGGER tr_parent_delete BEFORE DELETE ON parent
      FOR EACH ROW
      BEGIN
        DELETE FROM child WHERE id = OLD.specialChildrenId;
      END;
    |
    
    delimiter ;