zhaojp0 2019-06-28
最近在做项目的数据库迁移,从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