如何在暂存中添加删除级联 table
How to add delete cascade on staging table
这里是我如何创建 tables:
CREATE TABLE TABLE_A(
id uuid NOT NULL, UNIQUE
name text
);
CREATE TABLE TABLE_B(
id uuid NOT NULL, UNIQUE
name text
);
-- custom realization of many-to-many association
CREATE TABLE TABLE_A_B(
id uuid NOT NULL, UNIQUE
a_id uuid REFERENCES TABLE_A(id) ON UPDATE CASCADE,
B_id uuid REFERENCES TABLE_B(id) ON UPDATE CASCADE
);
我已经创建了 table,现在无法通过添加 ON DELETE CASCADE 来更新它。
我现在需要将 ON DELETE CASCADE 添加到暂存 table TABLE_A_B。怎么做?(
您使用ON DELETE CASCADE
:
CREATE TABLE TABLE_A_B(
id uuid NOT NULL UNIQUE,
a_id uuid REFERENCES TABLE_A(id) ON UPDATE CASCADE ON DELETE CASCADE,
B_id uuid REFERENCES TABLE_B(id) ON UPDATE CASCADE ON DELETE CASCADE
);
Here 是一个 db<>fiddle,它修复了您代码中的一些拼写错误。
特别是,外键引用应该是 主键 。尽管允许使用唯一键,但主键的目的实际上是识别单独的行——一个主要用途是用于外键引用。
编辑:
如果约束已经存在,则执行以下操作。
首先,获取他们的名字:
select *
from information_schema.table_constraints
where constraint_type = 'FOREIGN KEY' and table_name = 'table_a_b';
注意:您可以指定名称以跳过此步骤。
然后删除现有的外键约束:
alter table table_a_b
drop constraint table_a_b_a_id_fkey;
最后,添加一个新的:
alter table table_a_b
add constraint fk_table_a_b_a
foreign key (a_id) references table_a(id)
on update cascade
on delete cascade;
这里是我如何创建 tables:
CREATE TABLE TABLE_A(
id uuid NOT NULL, UNIQUE
name text
);
CREATE TABLE TABLE_B(
id uuid NOT NULL, UNIQUE
name text
);
-- custom realization of many-to-many association
CREATE TABLE TABLE_A_B(
id uuid NOT NULL, UNIQUE
a_id uuid REFERENCES TABLE_A(id) ON UPDATE CASCADE,
B_id uuid REFERENCES TABLE_B(id) ON UPDATE CASCADE
);
我已经创建了 table,现在无法通过添加 ON DELETE CASCADE 来更新它。 我现在需要将 ON DELETE CASCADE 添加到暂存 table TABLE_A_B。怎么做?(
您使用ON DELETE CASCADE
:
CREATE TABLE TABLE_A_B(
id uuid NOT NULL UNIQUE,
a_id uuid REFERENCES TABLE_A(id) ON UPDATE CASCADE ON DELETE CASCADE,
B_id uuid REFERENCES TABLE_B(id) ON UPDATE CASCADE ON DELETE CASCADE
);
Here 是一个 db<>fiddle,它修复了您代码中的一些拼写错误。
特别是,外键引用应该是 主键 。尽管允许使用唯一键,但主键的目的实际上是识别单独的行——一个主要用途是用于外键引用。
编辑:
如果约束已经存在,则执行以下操作。
首先,获取他们的名字:
select *
from information_schema.table_constraints
where constraint_type = 'FOREIGN KEY' and table_name = 'table_a_b';
注意:您可以指定名称以跳过此步骤。
然后删除现有的外键约束:
alter table table_a_b
drop constraint table_a_b_a_id_fkey;
最后,添加一个新的:
alter table table_a_b
add constraint fk_table_a_b_a
foreign key (a_id) references table_a(id)
on update cascade
on delete cascade;