我在 MySQL Workbench 中创建了表,如下所示:
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;
产品表:
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
表时,我得到:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (
srdjank
.Ordrelinje
, CONSTRAINTOrdrelinje_fk
FOREIGN KEY (Ordre
) REFERENCESOrdre
(OrdreID
))
我看过有关此主题的其他帖子,但没有运气。 我是否在监督某些事情或知道要做什么?
最佳答案
取自 Using FOREIGN KEY Constraints
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.
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.
因此,您的错误错误代码:1452。无法添加或更新子行:外键约束失败
本质上意味着,您正在尝试向Ordrelinje添加一行
Ordre
表中不存在匹配行 (OrderID) 的 code> 表。
您必须首先将该行插入 Ordre
表中。
关于mysql - 错误 1452 : Cannot add or update a child row: a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59496227/