Home > Enterprise >  produce an error Error Code: 1215. Cannot add foreign key constraint in mysql
produce an error Error Code: 1215. Cannot add foreign key constraint in mysql

Time:04-27

i made 2 tables like this,

CREATE TABLE personal (
id INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50),
created_at DATETIME);


CREATE TABLE personal_details (
id INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
personal_id INT(255),
tittle VARCHAR(10) NOT NULL,
family_name VARCHAR(50) NOT NULL, 
given_name VARCHAR(50) NOT NULL,
place_of_birth VARCHAR(50) NOT NULL,
date_of_birth DATE NOT NULL,
gender VARCHAR(25) NOT NULL,
country_citizen VARCHAR(50) NOT NULL,
national_identity_number INT(50) NOT NULL,
passport_no INT(50) NOT NULL,
issue_date DATE NOT NULL,
expiry_date DATE NOT NULL,
FOREIGN KEY (personal_id) REFERENCES personal(id)
);

but it returns an error like this Error Code: 1215. Cannot add foreign key constraint

even tough i already follow this solution from another question

https://stackoverflow.com/a/16969116/17067132

CodePudding user response:

I am a bit confused aboud the use scholarship_uiii in between the two CREATE-statements.

But the reason for the error is that you are missing the UNSIGNED for your personal_id field. So your second CREATE-statement should read:

CREATE TABLE personal_details (
id INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
personal_id INT(255) UNSIGNED,
tittle VARCHAR(10) NOT NULL,
family_name VARCHAR(50) NOT NULL, 
given_name VARCHAR(50) NOT NULL,
place_of_birth VARCHAR(50) NOT NULL,
date_of_birth DATE NOT NULL,
gender VARCHAR(25) NOT NULL,
country_citizen VARCHAR(50) NOT NULL,
national_identity_number INT(50) NOT NULL,
passport_no INT(50) NOT NULL,
issue_date DATE NOT NULL,
expiry_date DATE NOT NULL,
FOREIGN KEY (personal_id) REFERENCES personal(id)
);
  • Related