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:
1234567891011121314 |
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.
1234 |
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:
Https://stackoverflow.com/questions/22013511/mysql-error-1215-hy000-cannot-add-foreign-key-constraint
That is to say, my above guess is correct!
Take a look at the unique test:
Transferred from: http://www.cnblogs.com/Andy963/p/7634537.html
The last thing to note is that the foreign key must be the primary key or the unique key of the other table (that is, either set the column as the primary key or create a unique index)
PowerDesigner establish a primary key no longer described, the steps to establish a unique index are as follows
Select a column as unique index.
As for the establishment of foreign keys as follows:
Double-click the connector between the table and the tables
MySQL Error 1215 (HY000): Cannot add foreign KEY constraint resolution when you execute a SQL file with a foreign key