ERROR 1215 (HY000): Cannot add foreign KEY constraint
Recently encountered this error in the construction of the table, and then found the next find a solution, record:
Two tables were originally to be built:
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)
);
The following prompt appears:
Then began to surf the internet, and some said that the engine was used for different reasons, looked under mine, the two engines are identical,
Some say one is int, because after adding auto_increment, actually become int undesigned, since become
int undesigned that I also set into undesigned, and then insert, error Still,
At last I thought of the ID in the department table above, just shaping, probably not unique,
and added primary key.
create table department(
id int primary key,
name varchar(20)
);
Test again, found to be able to create the table normally
The specific principle here is not clear, the above is only speculation, hereby recorded
If you find a reason to update!
Update:
That is to say, my above guess is correct!
Take a look at the unique test:
MySQL ERROR 1215 (HY000): Cannot add foreign KEY constraint