数据库
首页 > 数据库> > 在MySQL中创建外键会产生错误:

在MySQL中创建外键会产生错误:

作者:互联网

我正在尝试在MySQL中的表上创建外键,但遇到一个奇怪的错误,即在我的任何搜索中似乎都没有多少信息.

我正在创建密钥(从mysql workbench 5.2发出):

ALTER TABLE `db`.`appointment` 
  ADD CONSTRAINT `FK_appointment_CancellationID`
  FOREIGN KEY (`CancellationID` ) REFERENCES `db`.`appointment_cancellation` (`ID` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION
, ADD INDEX `FK_appointment_CancellationID` (`CancellationID` ASC) ;

在这一点上我得到错误:

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (alarmtekcore., CONSTRAINT FK_lead_appointment_CancellationID FOREIGN KEY (CancellationID) REFERENCES lead_appointment_cancellation (`)

我检查了here

但表格中没有数据.

解决方法:

您不能将外键约束应用于父表中不存在的已有数据的列.

如果运行以下命令来填充约会表,则以后应该可以应用外键:

INSERT INTO appointment_cancellation
SELECT DISTINCT a.CancellationID
  FROM appointment

标签:foreign-keys,sql,mysql,mysql-error-1452
来源: https://codeday.me/bug/20191106/1999549.html