问题
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 (colleges):
I am trying to alter 1st table and add a foreign key that references id of a 2nd table:
ALTER TABLE users
ADD CONSTRAINT FOREIGN KEY (collegelinkId)
REFERENCES databaseName.colleges (id);
Which fails with error (errno: 150 "Foreign key constraint is incorrectly formed").
The only parameter that is different between these two tables is auto_increment. However, I can not add auto_increment to my users table collegelinkId column since its id is already set to auto_increment.
回答1:
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.
回答2:
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;
回答3:
- 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 TABLEswithout FKs, thenALTER ... ADD ... FKs- Be sure the do the
CREATEsin just the right order.
A side note: In INT(2), the (2) is irrelevant. All INTs are 4 bytes.
来源:https://stackoverflow.com/questions/56972619/mysql-5-5-errno-150-foreign-key-constraint-is-incorrectly-formed