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
删除父行时,我想删除子行。有什么办法可以在删除级联时触发此触发器?
我假设(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);