简体   繁体   English

MYSQL错误#1452

[英]MYSQL Error # 1452

I have two tables 我有两张桌子

One is Customer table With --- 一个是客户表---

CustomerID INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
Name CHAR(50) NOT NULL
Address CHAR (100) Not NULL
CITY CHAR (30) Not NULL

Then I have another Table called Orders with ---- 然后我有另一个表叫----

OrdersID  INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
CustomerID INT UNSIGNED NOT NULL
Amount FLOAT(6,2)
Date DATE NOT NULL

Now I am trying to add a foreign Key for CustomerID and REFERENCE Customers(CustomerID) 现在,我尝试为CustomerID和REFERENCE Customer(CustomerID)添加外键

I am using this command but am getting a #1452 - Cannot add or update a child row: a foreign key constraint fails 我正在使用此命令,但收到#1452-无法添加或更新子行:外键约束失败

ALTER TABLE LA_Orders
ADD CONSTRAINT fk_CustomerID FOREIGN KEY (CustomerID) REFERENCES LA_Customers(CustomerID)

I have already made sure InnoDB matches. 我已经确保InnoDB匹配。

Any help would much appreciated. 任何帮助将不胜感激。

This would occur if LA_Orders already has data and has invalid CustomerID columns. 如果LA_Orders已经具有数据并且具有无效的CustomerID列,则会发生这种情况。

You can find them using: 您可以使用以下方法找到它们:

select lo.*
from LA_Orders lo
where lo.CustomerID not in (select lc.CustomerID from LA_Customers lc);

(Actually, this assumes that LA_Customers(CustomerID) is not NULL . It should be a primary key, so that should be true.) (实际上,这假设LA_Customers(CustomerID)不是NULL 。它应该是主键,所以应该为true。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM