PostgreSQL级联列(非外键)

问题描述 投票:0回答:1
create table parent (
    child_type not null  
    child_id not null
);
create table child1(id not null);
create table child2(id not null);
create table child3(id not null);

并且表父级中有一些行是这样的:

child_type,child_id
"child1",1
"child1",2
"child2",1
"child3",1

删除父行时,我想删除子行。有什么办法可以在删除级联时触发此触发器?

sql postgresql sql-delete cascade
1个回答
0
投票

我假设(child_type,child_id)parent的主键

您创建这样的关联:

create table child1(
  child_type VARCHAR DEFAULT 'child1', 
  id INT not null
  FOREIGN KEY (child_type,id) REFERENCES parent(child_type, id) ON DELETE CASCADE
);
create table child2(
  child_type VARCHAR DEFAULT 'child2', 
  id INT not null
  FOREIGN KEY (child_type,id) REFERENCES parent(child_type, id) ON DELETE CASCADE
);
create table child3(
  child_type VARCHAR DEFAULT 'child3', 
  id INT not null
  FOREIGN KEY (child_type,id) REFERENCES parent(child_type, id) ON DELETE CASCADE
);

您不能仅在父级的复合PK的子级引用部分中包含id;子级必须具有与父级PK相同的N列和相同的值]


FWIW,这个表结构真的很古怪,它可能会四处咬你。喜欢一些更普通的东西,例如:

create table parent (
    id not null  
);
create table child1(id, parent_id REFERENCES parent.id);
create table child2(id, parent_id REFERENCES parent.id);
create table child3(id, parent_id REFERENCES parent.id);
© www.soinside.com 2019 - 2024. All rights reserved.