错误1452:无法添加或更新子行:外键约束失败 [英] ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

查看:424
本文介绍了错误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外国密钥(Ordre))参考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 fails本质上意味着,您正在尝试向Ordrelinje表中添加一行,而Ordre表中没有匹配的行(OrderID).

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.

这篇关于错误1452:无法添加或更新子行:外键约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆