MySQL 5.5 errno: 150 “Foreign key constraint is incorrectly formed”

前端 未结 3 1593
独厮守ぢ
独厮守ぢ 2021-01-16 20:25

There are plenty of questions regarding this error but I can\'t seem to find any similar scenario to what I have.

My 1st table (users):

My 2nd table

相关标签:
3条回答
  • 2021-01-16 20:37

    We would expect to see this error if the types of the primary and foreign key did not match exactly. While both appear to be integer with a width of 1, my guess here is that one of the INT columns in the key relationship is unsigned, while the other is signed. A possible fix would be to make both columns unsigned:

    ALTER TABLE users MODIFY collegelinkId INT(10) UNSIGNED NOT NULL;
    ALTER TABLE college MODIFY id INT(10) UNSIGNED NOT NULL;
    

    Edit:

    I was wrong, as evidenced by your latest comments under my answer. Another possibility is that you created your two tables using different database engines. For example, if you created users using InnoDB, but college using MyISAM, you could still get this error. To fix this, change the engine(s) on the tables to the same type.

    Note that yet another possibility would be that the two columns had different collations. But, that's really a moot point here, since both columns are numeric, not text.

    0 讨论(0)
  • 2021-01-16 20:38

    Since the columns are of the same type, it's worth to check the engine type as @Tim Biegeleisen suggested.

    Changing engine type fixed the issue.

    ALTER TABLE users
    ENGINE=InnoDB;
    
    0 讨论(0)
  • 2021-01-16 20:45
    • Verify that the datatypes match (except for PRIMARY KEY).
    • Verify that both tables are ENGINE=InnoDB.

    Even after that, error 150 can still occur. 3 ways around it:

    • Disable FKs while creating the tables, then re-enable.
    • CREATE TABLEs without FKs, then ALTER ... ADD ... FKs
    • Be sure the do the CREATEs in just the right order.

    A side note: In INT(2), the (2) is irrelevant. All INTs are 4 bytes.

    0 讨论(0)
提交回复
热议问题