I'm trying to add foreign keys to my two tables Problem and File. These are the CREATE queries. And both tables are created successfully:
CREATE TABLE lpsolve.tbl_file (
id INT(11) NOT NULL AUTO_INCREMENT,
problem_id INT(11) DEFAULT NULL,
title VARCHAR(255) DEFAULT NULL,
description VARCHAR(255) DEFAULT NULL,
type VARCHAR(255) DEFAULT NULL,
create_time DATETIME DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB
AUTO_INCREMENT = 1
CHARACTER SET latin1
COLLATE latin1_swedish_ci;
CREATE TABLE lpsolve.tbl_probem (
id INT(11) NOT NULL AUTO_INCREMENT,
title VARCHAR(255) DEFAULT NULL,
description VARCHAR(255) DEFAULT NULL,
create_time DATETIME DEFAULT NULL,
number_of_files INT(11) DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB
AUTO_INCREMENT = 1
CHARACTER SET latin1
COLLATE latin1_swedish_ci;
But when I try to add the following constraint I get the Error 1215 Error. This is the add constraint query:
ALTER TABLE tbl_file
ADD CONSTRAINT fk_problem_file
FOREIGN KEY (problem_id)
REFERENCES tbl_problem(id)
ON DELETE CASCADE
ON UPDATE RESTRICT
The query does not work even by removing the ON DELETE CASCADE
and ON UPDATE RESTRICT
either. There are a couple of similar problems mentioned in Stack Overflow but they did not answer my problem unfortunately.
Error message:
Cannot add foreign key constraint