MySQL ERROR 1215 (HY000): Cannot add foreign KEY constraint

Source: Internet
Author: User



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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.