SQL 级联删除查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3583459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:20:57  来源:igfitidea点击:

Cascade Delete Query

sqloracle

提问by Nits

I have three tables. Product, Company, Employee

我有三张桌子。产品、公司、员工

ProductId of Product table is foregin key for Company and CompanyId of Company table is foregin key for Employee

Product 表的 ProductId 是 Company 的外键,Company 表的 CompanyId 是 Employee 的外键

So on deleting ProductId from Product table, all the related records in other tables should delete. But I can't touch schema(can't use alter table). How should I write the query in that case..

因此,在从 Product 表中删除 ProductId 时,其他表中的所有相关记录都应删除。但我无法触摸架构(不能使用更改表)。在这种情况下我应该如何编写查询..

回答by Erich Kitzmueller

If you can't add constraints that propagates the delete, you have to write all the necessary deletes yourself:

如果您无法添加传播删除的约束,则必须自己编写所有必要的删除:

delete employee where companyid in (select companyid from company c where productid = xxx);
delete company where productid=xxx;
delete product where productid=xxx;

回答by Pravin Satav

Try this option. I don't have environment to test this. I guess with some changes it should work at your end.

试试这个选项。我没有环境来测试这个。我想通过一些更改,它应该可以在您的最后工作。

DELETE Product,Company,Employee 
FROM 
user LEFT JOIN items ON product.productid = company.productid 
LEFT JOIN orders ON company.productid = product.productid 
WHERE product.productid = [$productid]