繁体   English   中英

与外键和删除级联有关的MySQL问题

[英]Mysql Issue Related to foreign key and on delete cascade

我有4个sql表。

create table general(regno int NOT NULL primary key);

create table company_information(cregno int NOT NULL primary key);

create table company_jobs (jcode int NOT NULL primary key, cregno int , foreign key(cregno) references company_information(cregno));

create table applied(cregno int ,jcode int, regno int, foreign key(regno) references general(regno), foreign key(jcode) references company_jobs(jcode));

我需要做的就是在应用表具有一定价值时从表company_jobs中删除。 实际上,所有表都必须具有适用于表的值,才能具有从表结构中可以看到的值。 我使用以下命令添加了DELETE CASCADE约束:

alter table company_jobs add constraint fk_cregno13 foreign key(cregno) references company_information (cregno) on delete cascade;

alter table applied add constraint fk_jcode16 foreign key(jcode) references company_jobs(jcode) on delete cascade;

alter table applied add constraint fk_regno14 foreign key(regno) references general(regno) on delete cascade;

但是不幸的是它不能正常工作,当我给出以下命令时,我得到了这个错误。

mysql> delete from company_jobs;

ERROR 1451(23000):无法删除或更新父行,外键constrai NT失败( testapplied ,约束applied_ibfk_2外键( jcode )RE FERENCES company_jobsjcode ))

如果有人可以,请帮助我。 谢谢

应用于Company_job的从表指向的第一个外键没有任何级联规则,因此它简单地阻止了从company_job的删除;

看到mysql dump bellow

ALTER TABLE `applied`
  ADD CONSTRAINT `applied_ibfk_1` FOREIGN KEY (`regno`) REFERENCES `general` (`regno`),
  ADD CONSTRAINT `applied_ibfk_2` FOREIGN KEY (`jcode`) REFERENCES `company_jobs` (`jcode`),
  ADD CONSTRAINT `fk_jcode16` FOREIGN KEY (`jcode`) REFERENCES `company_jobs` (`jcode`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_regno14` FOREIGN KEY (`regno`) REFERENCES `general` (`regno`) ON DELETE CASCADE;

您需要先删除外键,或者重新创建没有第一个外键的表

ALTER TABLE 'applied' DROP CONTRAINT 'applied_ibfk_2';

创建applied表时,创建了2个外键。

在那之后,您已经向该表添加了另外两个外键。

如您所见,该错误引用了一个名为applied_ibfk_2的外键,它不是您在创建之后添加的外键。

因此,此刻在该表上有4个外键约束。

因此,您必须删除在创建表时创建的2个外键(具有预定义的名称),然后一切正常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM