MySQL 添加外鍵失敗 ERROR 1452

來源:互聯網
上載者:User

今天在學習資料庫添加外鍵的時候,遇到了問題

我先建立了兩個表  orders 和 order_items  ,儲存引擎都是InnoDB,且都有orderid這個屬性(類型完全一樣),但是我使用命令

  1. alter table order_items   
  2. add foreign key (orderid) references orders (orderid); 

添加外鍵的時候 出現了錯誤

ERROR 1452 : Cannot add or update a child row: a foreign key constraint fails   

最後才發現,原來是我的order_items表中已經存在了資料,且orderid這個屬性和orders中的不對應,因此如果添加外鍵,就會導致錯誤

此時解決的辦法不外乎兩個:

1.刪除資料,再添加外鍵

2.在orders中添加對應的項,再添加外鍵

 

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.