mysqlsqlheidisql

mysql Foreign key constraint is incorrectly formed error


table1 is the parent table with a column ID and table2 has a column IDFromTable1.

Why when I put a FK on IDFromTable1 to ID in table1 do I get Foreign key constraint is incorrectly formed error?

(I would like to delete the table2 record if the table1 record gets deleted.)

ALTER TABLE `table2`  
   ADD CONSTRAINT `FK1` 
      FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`) 
      ON UPDATE CASCADE 
      ON DELETE CASCADE;

Both tables' engines are InnoDB. Both colmnns are type char. ID is the primary key in table1.


Solution

  • I ran into this same cryptic error. My problem was that the foreign key column and the referencing column were not of the same type or length.

    The foreign key column was SMALLINT(5) UNSIGNED

    The referenced column was INT(10) UNSIGNED

    Once I made them both the same exact type, the foreign key creation worked perfectly.