且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除表中包含指向其他表的外键的行

更新时间:2023-01-29 09:57:46

首先,作为一次性数据清理练习,删除孤立的行,例如

First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

DELETE 
  FROM ReferencingTable 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM MainTable AS T1
                    WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                  );

其次,作为一次性模式更改练习,将 ON DELETE CASCADE 引用操作添加到引用表上的外键,例如

Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

ALTER TABLE ReferencingTable ADD 
   CONSTRAINT fk__ReferencingTable__MainTable 
      FOREIGN KEY (pk_col_1)
      REFERENCES MainTable (pk_col_1)
      ON DELETE CASCADE;

然后,当引用表中的行被删除时,引用表中的行将永远被删除.

Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.