select version(); 5.7.22
drop table if exists Models; CREATE TABLE Models ( ModelID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, Name VARCHAR(40) NOT NULL, PRIMARY KEY (ModelID) );
drop table if exists Orders; CREATE TABLE Orders ( ID SMALLINT UNSIGNED NOT NULL PRIMARY KEY, ModelID SMALLINT UNSIGNED NOT NULL, Description VARCHAR(40), FOREIGN KEY (ModelID) REFERENCES Models (ModelID) ON DELETE cascade );
insert into Orders(Id,ModelID,Description) values (1,1,'a');
異常:[2018-07-31 11:08:01] 23000 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)
原因:通不過on delete cascade 的外鍵約束檢查
insert into Models(ModelID,Name) values (1,'a'); insert into Orders(Id,ModelID,Description) values (1,1,'a');
select * from Models; 1 a select * from Orders; 1 1 a
delete from Orders where id = 1;
select * from Models; 1 a select * from Orders; 为空
delete from Models where ModelID = 1;
select * from Models; 为空 select * from Orders; 为空
update Orders set ModelID = 3 where ID =1;
異常:[2018-07-31 12:33:02] 23000 Cannot add or update a child row: a foreign key constraint fails (
bov.
Orders, CONSTRAINTINT
Orders_ibfk_1 FOREIGN KEY (
ModelID) REFERENCES
Models (
ModelID) ON DELETE CASCADE)
原因:通不過on delete cascade 的外鍵約束檢查
update Models set ModelID = 2 where ModelID =1;
異常:[2018-07-31 12:34:24 ] 23000 Cannot delete or update a parent row: a foreign key constraint fails (
bov.
Orders, CONSTRAINT
Orders_ibfk_1 FOREIGN KEY (##ModeModelID
#Mode ) REFERENCES Models
(ModelID
) ON DELETE CASCADE)原因:通不過on delete cascade 的外鍵約束檢查
測試案例-父子表都有數據,更新子表非外鍵
update Orders set Description = 'b' where ID =1;
select * from Orders; 1 1 b
測試案例-父子表都有數據,更新父表非主鍵
update Models set Name = 'c' where ModelID =1;
select * from Models; 1 c
相關文章:
以上是Mysq中l建立測試父表、子表及測試案例歸納總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!