错误 1452:无法添加或更新子行:外键约束失败

2021-11-20 00:00:00 sql mariadb mysql mysql-error-1452

我在 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) REFERENCES Ordre (OrdreID))

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (srdjank.Ordrelinje, CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (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.

相关文章