mysql執行帶外鍵的sql文件時出現mysql ERROR 1215 (HY000): Cannot add foreign key constraint的解決
阿新 • • 發佈:2018-04-14
原因 name logs cin not 另一個 https mys power
ERROR 1215 (HY000): Cannot add foreign key constraint
最近在建表時遇到了這個錯誤,然後找了下找到了解決辦法,記錄下:
本來是要建兩張表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
create table department(
id int ,
name varchar (20)
);
create table employee(
id int primary key auto_increment,
name varchar (20),
sex enum( ‘male‘ , ‘female‘ ) not null default ‘male‘ ,
age int ,
dep_id int ,
foreign key (dep_id) references department(id)
);
|
出現下面的提示:
然後開始上網查,有的說是用的引擎不同的原因,查看了下我的,兩引擎一模一樣,
又有的說一個是int ,因為加了auto_increment後,實際變成了int undesigned,既然變成了
int undesigned那我也設置成undesigned,再插入,錯誤依舊,
最後 我想到了上面的department表中的id,只是整形,可能不唯一,
然後加上了 primary key
1 2 3 4 |
create table department(
id int primary key ,
name varchar (20)
);
|
再次試驗,發現能正常創建表
這裏的具體原理是什麽還沒搞清楚,上面的也只是猜測,特此記錄
如果找到原因再更新!
更新:
https://stackoverflow.com/questions/22013511/mysql-error-1215-hy000-cannot-add-foreign-key-constraint
也就是說我上面 的猜測是正確的!
看看對unique的測試:
轉自:http://www.cnblogs.com/Andy963/p/7634537.html
以上要註意的就是最後一點原因外鍵必須是另一個表的主鍵或者唯一鍵(即要不把那個列設為主鍵要不就建立一個唯一索引)
powerdesigner建立主鍵不再介紹,建立唯一索引的步驟如下
選擇某列為unique index即可。
至於外鍵的建立如下:
雙擊表與表之間的連接線
mysql執行帶外鍵的sql文件時出現mysql ERROR 1215 (HY000): Cannot add foreign key constraint的解決