問題描述
我在 MySQL Workbench 中創(chuàng)建了表,如下所示:
I have created tables in MySQL Workbench as shown below :
ORDRE 表:
CREATE TABLE Ordre (
OrdreID INT NOT NULL,
OrdreDato DATE DEFAULT NULL,
KundeID INT DEFAULT NULL,
CONSTRAINT Ordre_pk PRIMARY KEY (OrdreID),
CONSTRAINT Ordre_fk FOREIGN KEY (KundeID) REFERENCES Kunde (KundeID)
)
ENGINE = InnoDB;
PRODUKT 表:
CREATE TABLE Produkt (
ProduktID INT NOT NULL,
ProduktBeskrivelse VARCHAR(100) DEFAULT NULL,
ProduktFarge VARCHAR(20) DEFAULT NULL,
Enhetpris INT DEFAULT NULL,
CONSTRAINT Produkt_pk PRIMARY KEY (ProduktID)
)
ENGINE = InnoDB;
和ORDRELINJE表:
CREATE TABLE Ordrelinje (
Ordre INT NOT NULL,
Produkt INT NOT NULL,
AntallBestilt INT DEFAULT NULL,
CONSTRAINT Ordrelinje_pk PRIMARY KEY (Ordre, Produkt),
CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID),
CONSTRAINT Ordrelinje_fk1 FOREIGN KEY (Produkt) REFERENCES Produkt (ProduktID)
)
ENGINE = InnoDB;
所以當(dāng)我嘗試將值插入 ORDRELINJE
表時,我得到:
so when I try to insert values into ORDRELINJE
table i get:
錯誤代碼:1452.無法添加或更新子行:外鍵約束失敗(srdjank
.Ordrelinje
, CONSTRAINT Ordrelinje_fk
FOREIGNKEY (Ordre
) REFERENCES Ordre
(OrdreID
))
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (
srdjank
.Ordrelinje
, CONSTRAINTOrdrelinje_fk
FOREIGN KEY (Ordre
) REFERENCESOrdre
(OrdreID
))
我看過關(guān)于這個主題的其他帖子,但沒有運氣.我是否在監(jiān)督某事或知道該怎么做?
I've seen the other posts on this topic, but no luck. Am I overseeing something or any idea what to do?
推薦答案
摘自 使用外鍵約束
外鍵關(guān)系涉及一個父表,其中包含中心數(shù)據(jù)值,以及具有相同值指向的子表回到它的父母.FOREIGN KEY 子句在子句中指定表.
Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table.
它將拒絕任何試圖創(chuàng)建的 INSERT 或 UPDATE 操作如果沒有匹配項,則為子表中的外鍵值父表中的候選鍵值.
It will reject any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.
所以你的錯誤 Error Code: 1452. Cannot add or update a child row: a foreign key constraint failed
本質(zhì)上意味著,你正試圖向你的 Ordrelinje
添加一行Ordre
表中不存在匹配行 (OrderID) 的 code> 表.
So your error Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails
essentially means that, you are trying to add a row to your Ordrelinje
table for which no matching row (OrderID) is present in Ordre
table.
您必須先將該行插入到您的 Ordre
表中.
You must first insert the row to your Ordre
table.
這篇關(guān)于錯誤 1452:無法添加或更新子行:外鍵約束失敗的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!