So I\'m trying to add Foreign Key constraints to my database as a project requirement and it worked the first time or two on different tables, but I have two tables on which
For me it was - you can't omit prefixing the current DB table if you create a FK for a non-current DB referencing the current DB:
USE currrent_db;
ALTER TABLE other_db.tasks ADD CONSTRAINT tasks_fk FOREIGN KEY (user_id) REFERENCES currrent_db.users (id);
If I omit "currrent_db." for users table, I get the FK error. Interesting that SHOW ENGINE INNODB STATUS; shows nothing in this case.
I had similar error with two foreign keys for different tables but with same key names! I have renamed keys and the error had gone)
I had same problem and the solution was very simple. Solution : foreign keys declared in table should not set to be not null.
reference : If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL. (ref )
I had set one field as "Unsigned" and other one not. Once I set both columns to Unsigned it worked.
Please ensure that both the tables are in InnoDB format. Even if one is in MyISAM format, then, foreign key constraint wont work.
Also, another thing is that, both the fields should be of the same type. If one is INT, then the other should also be INT. If one is VARCHAR, the other should also be VARCHAR, etc.