Deleting hierarchical data in SQL table

后端 未结 8 2081
遥遥无期
遥遥无期 2020-12-14 09:43

I have a table with hierarchical data.
A column \"ParentId\" that holds the Id (\"ID\" - key column) of it\'s parent.

When deleting a row, I want to delete all c

8条回答
  •  既然无缘
    2020-12-14 10:23

    Add a foreign key constraint. The following example works for MySQL (syntax reference):

    ALTER TABLE yourTable
    ADD CONSTRAINT makeUpAConstraintName
    FOREIGN KEY (ParentID) REFERENCES yourTable (ID)
    ON DELETE CASCADE;
    

    This will operate on the database level, the dbms will ensure that once a row is deleted, all referencing rows will be deleted, too.

提交回复
热议问题