Deleting hierarchical data in SQL table

后端 未结 8 2076
遥遥无期
遥遥无期 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:18

    Depends on your database. If you are using Oracle, you could do something like this:

    DELETE FROM Table WHERE ID IN (
      SELECT ID FROM Table
      START WITH ID = id_to_delete
      CONNECT BY PRIOR.ID = ParentID
    )
    

    ETA:

    Without CONNECT BY, it gets a bit trickier. As others have suggested, a trigger or cascading delete constraint would probably be easiest.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题