外鍵DDL在Oracle運行正常,在mysql報異常以及處理方案
發(fā)表時間:2023-07-16 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]記一個Mysql外鍵約束設(shè)計缺陷背景信息最近在做項目的數(shù)據(jù)庫遷移,從Oracle到Mysql,一個外鍵約束在Oracle運行正常,在mysql報異常。(因為才接手沒幾天,對業(yè)務(wù)和框架不熟,在處理問題...
記一個Mysql外鍵約束設(shè)計缺陷
背景信息
最近在做項目的數(shù)據(jù)庫遷移,從Oracle到Mysql,一個外鍵約束在Oracle運行正常,在mysql報異常。(因為才接手沒幾天,對業(yè)務(wù)和框架不熟,在處理問題時花了很多時間。)
[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)
Oracle的DDL
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
Mysql的DDL
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');
在執(zhí)行最后一句時,報異常
[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就不會認(rèn)為其一定不等,而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
總結(jié)
Mysql的外鍵約束設(shè)計有缺陷,如果不同單位的字段一定不同,應(yīng)在添加FOREIGN KEY就報異常,而不是模棱兩可的因為類型不同,但實際數(shù)值相等,其判斷為不等于。
數(shù)據(jù)庫表維護(hù)的時候,不同table中,意義相同的column,類型一定要保持一致。
以上就是外鍵DDL在Oracle運行正常,在mysql報異常以及解決方案的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
學(xué)習(xí)教程快速掌握從入門到精通的SQL知識。