简体   繁体   中英

Cannot add foreign key in MySQL?

Here is the statement I am executing and related error, any hints what is wrong and how to debug further is appreciated. Using MySQL Workbench/MySQL.

Especially confused what means child row here? How foreign key related to child row? And what is the child row here?

ALTER TABLE Orders
ADD CONSTRAINT fk_Customer FOREIGN KEY (CustomerID) 
REFERENCES Customers(CustomerID) 

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails ( test . #sql-ff_2 , CONSTRAINT fk_Customer FOREIGN KEY ( CustomerID ) REFERENCES Customers ( CustomerID ))

This error means that your tables contain data that should not be allowed by the foreign key you're trying to create. You could use a query to find them:

SELECT *
FROM   orders
WHERE  customerid NOT IN (SELECT customerid FROM customers)

If you're sure these rows are indeed faulty, you could use a similar delete statement to remove them:

DELETE FROM orders
WHERE  customerid NOT IN (SELECT customerid FROM customers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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