MySQL添加外键失败ERROR 1452的解决

[sql] 
alter table order_items   
add foreign key (orderid) references orders (orderid);  
  www.2cto.com  
添加外键的时候 出现了错误
[sql] 
ERROR 1452 : Cannot add or update a child row: a foreign key constraint fails   
 
最后才发现,原来是我的order_items表中已经存在了数据,且orderid这个属性和orders中的不对应,因此如果添加外键,就会导致错误
此时解决的办法不外乎两个:
 
1.删除数据,再添加外键
2.在orders中添加对应的项,再添加外键

猜你喜欢

转载自zk-yangyan.iteye.com/blog/2162561