开发者

Delete row when a table has an FK relationship

开发者 https://www.devze.com 2023-01-26 03:22 出处:网络
Hi I have 开发者_开发百科2 tables Document and Project. DocumentID is an FK in the Project table.

Hi I have 开发者_开发百科2 tables Document and Project.

DocumentID is an FK in the Project table.

Using sql How can I delete Document Records in the Document table, and also remove their corresponding records in the Project table.

Thanks


When creating the foreign key, specify is as a ON DELETE CASCADE table constraint.

This constraint means that when a document is deleted, all project rows referencing it as a foreign key will also be deleted.


delete 
  from projects 
 where documentsFK = (
                      select documentFK 
                        from documents 
                       where documentsFK > 125
                     );

delete 
  from documents 
 where documentsFK > 125;

EDIT

delete 
  from projects 
 where documentsFK in (
                       select documentFK 
                         from documents 
                        where documentsFK > 125
                      );

delete 
  from documents 
 where documentsFK > 125;
0

精彩评论

暂无评论...
验证码 换一张
取 消