1. 程式人生 > >ERROR 1215 (HY000): Cannot add foreign key constraint

ERROR 1215 (HY000): Cannot add foreign key constraint

mod alter hiberna structure 無意中 jsb ron b2c har

MySQL中在為一個varchar類型數據列添加外鍵時,會發生上面所示的錯誤,這裏我google了一下,感覺它們碰到的問題跟我這個說的有點不相幹,嘗試了多種方式後來才發現是:主表(table1)所對應關聯的數據列必須為unique才可以

[sql] view plain copy
  1. #指定主表dept列unique約束
  2. alter table table1 modify dept varchar(5) not null unique.

這裏我創建了兩張表(table2、 table1),表結構如圖所示:

技術分享

為什麽要增加unique約束?

這個問題我是在hibernate中指定一對一有連接表關聯時無意中註意到的,沒有unique約束一般都會失敗。至於到底為什麽看下面這張圖應該就清楚了:

技術分享


ERROR 1215 (HY000): Cannot add foreign key constraint