由于一个表中的数据,从多个表中删除行

时间:2019-05-31 04:34:35

标签: sql

我有多个表需要从中删除行,并且这些表都取决于一个表中的数据。例如,我有一个用户表,在用户表中,用户有一个UserId。我正在尝试摆脱所有与其他表中的那个用户有关的所有数据。

例如,有一个Members表,并且在Members表中,Users表具有外键关系,因此它与UserId绑定。成员表可以具有与UserId关联的多个成员(一个用户可以是多个事物的成员,因此是一对多关系)。然后还有一个“权限”表,在“权限”表中,它与“成员”表具有外键关系。并且在该表中,成员可以具有多个权限(一个成员可以拥有多个权限,即一对多关系)。

我需要做的是从用户表中删除Permissions表中与所有与UserId有关的所有MemberId相关的所有行(即-Bob的UserId为7,并且在成员表他是3件事的成员,因此他具有3个与他的名称相关联的MemberId,并且在权限表中,这3个MemberId也具有与这3个MemberId相关的3个权限。我需要根据这3个MemberId删除所有9个权限行,然后根据1个UserId删除所有3个Member行,然后根据一个UserName删除一个UserId)。

我尝试了内部联接多个表,并将它们与联合连接起来,但是我很难将所有这些表绑定到一个UserId并通过逻辑流程传递该数据。

用户的UserId为7

User has UserId of 7

用户与3个MemberId相关联

User is is associated with 3 MemberId's

MemberId与多个PermissionId相关联

MemberId is associated with multiple PermissionId

因此,我需要删除所有那些PermissionId(我仅对User的MemberId进行了WHERE声明),MemberId的所有3个实例以及User。

1 个答案:

答案 0 :(得分:0)

If you are aware of UserID that you want to delete from different table, then this is easy to handle from table Users and Members. You need to use a Sub Query when you will delete records from Permissions table. But if there are relation (PK/FK) established between tables, you need to maintain some sequence as below-

Important Note: Delete is a risky operation unless you have proper Backup. So please try to execute scripts on test data first.

At first you have to delete records from Permission table with following script-

DELETE FROM Permissions
WHERE MemberID IN 
(
    SELECT MemberID FROM Members
    WHERE UserID = 7
)

In second step, you have to delete records from Members table as below-

DELEET FROM Member WHERE UserID = 7

In third step, you have to delete users from Users table as below-

DELETE from Users WHERE UserID = 7