【问题标题】:how to set a constraint that sets null on only one of the fields in the composite foreign key when the parent record is deleted?删除父记录时,如何设置仅在复合外键中的一个字段上设置 null 的约束?
【发布时间】:2022-01-14 13:47:16
【问题描述】:

我有 2 个 postgres 表。

表一: |id|user_id|master_team_id|role_id

表二: |uuid|user_id|master_team_id|编号

  • 表二中的master_team_id可以为空。
  • user_id 和 master_id 外键引用 user_id 和 表一中的 master_team_id。
  • 为了使表二中的 master_team_id 不为空,user_id 并且 master_team_id 组合必须存在于表一中。

当删除表一中的引用行时,如何添加一个约束,仅在表二的复合键(user_id,master_team_id)中将 master_team_id 设置为 null?

【问题讨论】:

  • 显示您的表定义。如果约束仅针对每个字段,那么您只需将on delete set null 用于相关字段。
  • 我只需要将 null 设置为其中一个字段。约束在 2 个字段上。

标签: sql postgresql constraints


【解决方案1】:

在 FK 约束中指定 ON DELETE SET NULL

https://www.techonthenet.com/sql_server/foreign_keys/foreign_delete_null.php

旁注:我建议在表 2 中添加一个名为“TableOneID”的新列,这样您就可以知道匹配记录是否存在。

【讨论】:

  • 我只需要将 null 设置为其中一列,但不能同时设置两者。我如何指定哪一列?不过,约束在 2 列上。
【解决方案2】:

你还不能这样做。

真是巧合。这样做的能力是 committed yesterday,并且(如果一切按计划进行的话)将包含在 v15 中,该版本将在近一年内到期。

您可以使用如下所示的触发器:

create table p (c1 int, c2 int, unique  (c1,c2));
create table c (c1 int, c2 int, r double precision);
alter table c add constraint fk99999 foreign key (c1,c2) references p (c1,c2);
create function update_c() returns trigger language plpgsql as $$
BEGIN
  update c set c2=null where c1=old.c1 and c2=old.c2;
  return old;
END; $$;
create trigger sdjflsfd before delete ON p for each row execute function update_c();

【讨论】:

  • 无论如何我可以通过触发器来实现这一点?
  • 我想是的。父级上更新子级的 BEFORE DELETE 触发器应该可以工作,并使用常规(删除时无操作)FK 约束来捕获竞争条件。
  • 你能举个例子来写这样的触发器吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2019-09-29
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多