简体   繁体   English

如何删除所有相关记录?

[英]How do I delete all related records?

I'm trying to delete a user and all the related records tied to him, and I have no clue how to use the SQL INNER JOIN statement, is there any way to do something in the style of:我正在尝试删除一个用户以及与他相关的所有相关记录,但我不知道如何使用 SQL INNER JOIN 语句,有什么方法可以执行以下操作:

DELETE * FROM tblUsers, tblEnrollment, tblLinkActivities, tblFullSchedule, tblSchedule, tblLinkMedical
WHERE [IDUser] = ?

(I know that's completely incorrect) (我知道这完全不正确)

My relationships chart looks like so:我的关系图如下所示:

关系

Would it be easier to use 6 delete commands?使用 6 个删除命令会更容易吗? Or is there another command that does that?或者是否有另一个命令可以做到这一点? Thanks a bunch..谢谢一堆..

Since you already have defined relationships with referential integrity, simply set the Cascade Delete Related Records option for each relationship.由于您已经定义了具有参照完整性的关系,只需为每个关系设置级联删除相关记录选项。

See https://support.office.com/en-us/article/create-edit-or-delete-a-relationship-dfa453a7-0b6d-4c34-a128-fdebc7e686af#__bmcascade请参阅https://support.office.com/en-us/article/create-edit-or-delete-a-relationship-dfa453a7-0b6d-4c34-a128-fdebc7e686af#__bmcascade

This way you only need to delete from tblUsers, all related records are deleted automatically.这样你只需要从 tblUsers 中删除,所有相关的记录都会被自动删除。

If you can't or don't want to do this, you need to run separate delete queries on the related tables before deleting the main record.如果您不能或不想这样做,则需要在删除主记录之前对相关表运行单独的删除查询。

There's no way to delete records in multiple tables at the same time in single sql query.无法在单个 sql 查询中同时删除多个表中的记录。 You need to write multiple delete statements.您需要编写多个删除语句。 The better way is to write an inner query with all tables involved and delete in each table.更好的方法是编写一个包含所有表的内部查询,并在每个表中删除。 For ex: delete from dept where DEPTNO IN (Select a.DEPTNO from emp a , dept b where a.DEPTNO=b.DEPTNO and a.DEPTNO=10) delete from emp where DEPTNO IN (Select a.DEPTNO from emp a , dept b where a.DEPTNO=b.DEPTNO例如:delete from dept where DEPTNO IN(从 emp a 中选择 a.DEPTNO,dept b where a.DEPTNO=b.DEPTNO and a.DEPTNO=10)从 emp where DEPTNO IN 中删除(从 emp a 中选择 a.DEPTNO, b 部门,其中 a.DEPTNO=b.DEPTNO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM