简体   繁体   English

禁止级联删除的外键约束

[英]foreign key constraints forbiding cascading delete

I have teams that can be assigned team members and people. 我有可以分配团队成员和人员的团队。 The team table and person tables already exist and can't be touched, I'm creating join tables to assign team members and team leads. 团队表和人员表已经存在并且无法使用,我正在创建联接表以分配团队成员和团队负责人。

I have one key constraint, a team lead must be a team member, and as long as someone is assigned as a team lead it should be impossible to remove them as a team member. 我有一个关键的约束,团队负责人必须是团队成员,而且只要有人被指定为团队负责人,就不可能将他们删除为团队成员。

My sql looks something like this (translating from a more complex table, forgive me if I mistyped my example since I'm writing it by hand) 我的sql看起来像这样(从一个更复杂的表进行翻译,请原谅我由于手工编写而输入了错误的示例)

CREATE TABLE TEAM_MEMBERS (id BIGINT NOT NULL,
  teamId BIGINT NOT NULL,
  personId BIGINT NOT NULL,
  PRIMARY KEY (id),
  KEY (teamId),
  KEY (personId)

  CONSTRAINT fk_team FOREIGN KEY (teamId) REFERENCES TEAM(id) ON DELETE CASCADE);

CREATE TABLE TEAM_LEAD (id BIGINT NOT NULL,
  teamId BIGINT NOT NULL,
  personId BIGINT NOT NULL,
  PRIMARY KEY (id),
  KEY (teamId),
  KEY (personId),
  CONSTRAINT fk_team_u FOREIGN KEY (teamId) REFERENCES TEAM (id) ON DELETE CASCADE,
  CONSTRAINT fk_child FOREIGN KEY (teamId, personId) REFERENCES TEAM_MEMBERS(teamId, personId)) ON DELETE RESTRICT;

This does not work. 这是行不通的。 When a team is removed I get a constraint violation, because it cascades the delete to team_members first, attempts to delete that, and discovers that team_lead is blocking it. 当团队被删除时,我遇到了约束冲突,因为它首先将删除级联到team_members,尝试删除它,并发现team_lead阻止了它。

My question, is there an easy way express some sort of order of operations here, to make sql understand that it should remove the team-lead first, or otherwise understand that it is not a constraint violation if it cascades the deletes entirely? 我的问题是,有没有一种简单的方法可以在这里表达某种操作顺序,以使sql理解它应该首先删除组长,或者以其他方式理解,如果它完全级联删除操作,这不是约束冲突?

I realize one solution would be to make teamLead a boolean on team_members rather then a separate join table. 我意识到一种解决方案是使teamLead成为team_members的布尔值,而不是单独的联接表。 For various reasons I would prefer not to do this, but it can be done if there is not another cleaner solution. 由于种种原因,我宁愿不这样做,但是如果没有其他更清洁的解决方案,则可以这样做。

Were using PostgreSQL on server, H2 for our testing, though we would prefer not to be tied in to a DB if possible. 我们在服务器H2上使用PostgreSQL进行测试,尽管我们希望在可能的情况下不要绑定到数据库。

This SQL constraint should not be here: 此SQL约束不应在此处:

CONSTRAINT fk_child FOREIGN KEY (teamId, personId) REFERENCES TEAM_MEMBERS(teamId, personId)) ON DELETE RESTRICT;

Your data model seems wrong: a team leader should not have a foreign key pointing to team members, but to a team only. 您的数据模型似乎是错误的:团队负责人不应具有指向团队成员的外键,而只能指向团队。

Could you please post the complete schema so we could provide a more complete answer? 您能否发布完整的架构,以便我们提供更完整的答案?

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

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