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

mysql ERROR 1215 (HY000): Cannot add foreign key constraint

add foreign 裏的 查看 image alt char 了解 can

ERROR 1215 (HY000): Cannot add foreign key constraint

最近在建表時遇到了這個錯誤,然後找了下找到了解決辦法,記錄下:

本來是要建兩張表:

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

create table department(
id int primary key,
name varchar(20) 
);

再次試驗,發現能正常創建表

技術分享

這裏的具體原理是什麽還沒搞清楚,上面的也只是猜測,特此記錄

如果找到原因再更新!

更新:

技術分享

也就是說我上面 的猜測是正確的!

看看對unique的測試:

技術分享

mysql ERROR 1215 (HY000): Cannot add foreign key constraint