我有三个这样的表:
create table parent (
key1 not null
key2 not null
primary key (key1, key2)
) engine=innodb;
create table child (
name
key1 not null
key2 not null
key3 not null
primary key (key1, key2, key3),
foreign key (key1) references parent(key1) on delete cascade,
foreign key (key2) references parent(key2) on delete cascade
) engine=innodb;
create table child_denormalization (
key1 not null
key2 not null
key3 not null
primary key (key1, key2, key3),
foreign key (key1) references child(key1) on delete cascade,
foreign key (key2) references child(key2) on delete cascade,
foreign key (key3) references child(key3) on delete cascade
) engine=innodb;
现在,父表行由key1和key2唯一标识,但是多个行可能具有相同的key1或key2值,但不能同时具有这两个值。
当我从父表中删除一行时,即使key2不同,子级中所有具有与被删除行相同key1值的行也会被删除。
是否有一种方法仅在所有外键均与删除的行匹配时删除级联?
我尝试删除“在删除级联上”,而是在父级删除之前添加触发器以手动从子级删除行,但是在child_key1上仍然出现外键约束错误。
答案 0 :(得分:1)
您可以定义复合外键,而不必单独定义它们:
create table parent (
key1 not null
key2 not null
primary key (key1, key2)
) engine=innodb;
create table child (
name
key1 not null
key2 not null
key3 not null
primary key (key1, key2, key3),
-- composite foreign key instead of individual keys
foreign key (key1, key2) references parent(key1, key2) on delete cascade
) engine=innodb;