发布网友 发布时间:2022-04-13 00:27
共3个回答
懂视网 时间:2022-04-13 04:49
最近在做项目的数据库迁移,从Oracle到Mysql,一个外键约束在Oracle运行正常,在mysql报异常。(因为才接手没几天,对业务和框架不熟,在处理问题时花了很多时间。)
[2018-08-01 13:34:19] [23000][1452] Cannot add or update a child row: a foreign key constraint fails (`bov`.`PRO_SITES_BRANDREQUEST`, CONSTRAINT `AA` FOREIGN KEY (`ID`) REFERENCES `PRO_SITES_SETUPREQUEST` (`ID`) ON DELETE CASCADE)
drop table Models; CREATE TABLE Models ( ModelID number(6) PRIMARY KEY, Name VARCHAR(40) ); drop table Orders; CREATE TABLE Orders ( ModelID number(8) PRIMARY KEY, Description VARCHAR(40), FOREIGN KEY (ModelID) REFERENCES Models (ModelID) ON DELETE cascade ); insert into Models(ModelID, Name) values (1,'model'); insert into Orders(ModelID,Description) values (1,'order');
select * from Models; 1 model select * from Orders; 1 order
drop table Models; CREATE TABLE Models ( ModelID decimal(6,0) PRIMARY KEY, Name VARCHAR(40) ); drop table Orders; CREATE TABLE Orders ( ModelID decimal(8,0) PRIMARY KEY, Description VARCHAR(40), FOREIGN KEY (ModelID) REFERENCES Models (ModelID) ON DELETE cascade ); insert into Models(ModelID, Name) values (1,'model'); insert into Orders(ModelID,Description) values (1,'order');
在执行最后一句时,报异常
[2018-08-01 14:06:16] [23000][1452] Cannot add or update a child row: a foreign key constraint fails (`bov`.`Orders`, CONSTRAINT `Orders_ibfk_1` FOREIGN KEY (`ModelID`) REFERENCES `Models` (`ModelID`) ON DELETE CASCADE)
原因:Models的ModelID是decimal(6,0),而Orders的ModelID是decimal(8,0),两个通过外键相连。因为类型不一致,mysql就不会认为其一定不等,而oracle可以做到不同类型的相容判等。
drop table Orders; CREATE TABLE Orders ( ModelID decimal(6,0) PRIMARY KEY, Description VARCHAR(40), FOREIGN KEY (ModelID) REFERENCES Models (ModelID) ON DELETE cascade ); insert into Orders(ModelID,Description) values (1,'order');
select * from Models; 1 model select * from Orders; 1 order
Mysql的外键约束设计有缺陷,如果不同单位的字段一定不同,应在添加FOREIGN KEY就报异常,而不是模棱两可的因为类型不同,但实际数值相等,其判断为不等于。
数据库表维护的时候,不同table中,意义相同的column,类型一定要保持一致。
相关文章:
MySQL外键约束方式_MySQL
MySQL的外键约束级联删除
相关视频:
猎豹网MySQL视频教程
热心网友 时间:2022-04-13 01:57
假设两个表A和B,B中定义了一个外键,它的d列reference到A表的c列。在往d列插数据的时候,其值在c列里面并不存在,于是触发这个错误。
热心网友 时间:2022-04-13 03:15
两个表之间有外键约束关系,但是外表中的某主键值在主表被引用列中不存在,所以造成这种情况.