问题描述
我在 MySQL Workbench 中创建了如下所示的表:
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;
所以当我尝试将值插入 ORDRELINJE
表时,我得到:
so when I try to insert values into ORDRELINJE
table i get:
错误代码:1452.无法添加或更新子行:外键约束失败(srdjank
.Ordrelinje
, CONSTRAINT Ordrelinje_fk
FOREIGNKEY (Ordre
) 参考 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
))
我看过关于这个主题的其他帖子,但没有运气.我是否在监督某事或知道该怎么做?
I've seen the other posts on this topic, but no luck. Am I overseeing something or any idea what to do?
推荐答案
取自使用外键约束
外键关系涉及一个父表,该表包含中心数据值,以及具有相同值指向的子表回到它的父级.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.
它将拒绝任何尝试创建的 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
本质上意味着,您正在尝试向 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.
这篇关于ERROR 1452:无法添加或更新子行:外键约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!