从不同的表中删除记录

时间:2017-07-27 09:32:11

标签: sql sql-server

你能帮我解决一下这个问题: 我有3个表:

Table Name1: Contact

cnt_id, CNTName

12,     test
13,     test2


Table Name2: Relation

cnt_id, r_grpid

12,     55
13,     55
13,     56

Table Name3: Group

grp_1d, 

55
56

我想要做的是当我从表GROUP中删除组ID 55时,表CONTACT上的记录会相应删除。但正如您所看到的,CNT_id 13也链接到另一个群组,在这种情况下CNT_id 13不应删除。

此致

3 个答案:

答案 0 :(得分:2)

如果您想使用查询或存储过程,这将有所帮助。

declare  @groupId  int =55

delete from  Contact where cnt_id in  (select C.cnt_id from Contact C
inner  join Relation R  on R.cnt_id=C.cnt_id  where R.r_grpid =@groupId)

delete from   Relation where  r_grpid =@groupId

delete from  Group where  r_grpid =@groupId

答案 1 :(得分:1)

可能是一个触发器可以帮助你,我在sql开发人员中做了以下:

insert into contact values (12, 'abc');
insert into contact values (13, 'def');

insert into relation values (12, 55);
insert into relation values (13, 55);

insert into grouptab values (55);

然后在sqlplus中打开一个会话

创建了一个触发器

SQL> CREATE OR REPLACE TRIGGER delete_data
  2  BEFORE delete
  3   ON grouptab
  4  REFERENCING NEW AS New OLD AS Old
  5  FOR EACH ROW
  6  DECLARE
  7  BEGIN
   delete from contact where contact_uid in (select contact_uid from relation where group_uid = :old.GROUP_uID);
END delete_data;

SQL> select * from contact;

CONTACT_UID CONTACT_NAME
----------- ------------------------------
         12 abc
         13 def

SQL> select * from relation;

CONTACT_UID  GROUP_UID
----------- ----------
         12         55
         13         55

SQL> select * from grouptab;

 GROUP_UID
----------
        55

SQL> delete from grouptab;

1 row deleted.

SQL> delete from contact;

0 rows deleted.

请尝试以下:

从关系rel中删除其中(55)中的group_uid和1 =(从contact_uid = rel.contact_uid的关系中选择count(*));

答案 2 :(得分:0)

如果关系中的cnt_id和r_grpid的组合是唯一的,您可以使用之前建议的查询,但在cnt_id上添加了一个额外的过滤器,如下所示:

declare  @groupId  int =55

delete from  Contact where cnt_id in  (select C.cnt_id from Contact C
inner  join Relation R  on R.cnt_id=C.cnt_id  where R.r_grpid =@groupId AND cnt_id not in (select cnt_id from Relation group by cnt_id having count(*) > 1))

delete from   Relation where  r_grpid =@groupId AND cnt_id not in (select cnt_id from Relation group by cnt_id having count(*) > 1)

delete from  Group where  r_grpid =@groupId