Mysql – setting a foreign key to an empty string

foreign keyinsertMySQL

I'm trying to set a foreign key to an empty string but i keep getting this error.

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`msis230`.`deptchair`, CONSTRAINT `deptchair_ibfk_1` FOREIGN KEY (`PROFESSORID`) REFERENCES `professor` (`PROFID`))

this is my code:

INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES ('SJ001', 'MSIS');
INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES ('', 'BIO');
INSERT INTO DEPTCHAIR 
VALUES ('JS001', 'PHY');
INSERT INTO DEPTCHAIR 
VALUES  ('NS001', 'MKT');
INSERT INTO DEPTCHAIR 
VALUES ('', 'ECO');

Best Answer

There are two approaches you can take

APPROACH #1 : Add to professor table

INSERT INTO professor (PROFID) VALUES ('');

Then, all INSERTs to DEPTCHAIR will work.

APPROACH #2 : Disable Foreign Key Check

SET foreign_key_checks = 0;
INSERT INTO DEPTCHAIR (PROFESSORID, DEPTID)
VALUES ('', 'BIO');
SET foreign_key_checks = 1;