MySQL Cannot Add Foreign Key Constraint

后端 未结 22 1824
时光取名叫无心
时光取名叫无心 2020-11-22 08:35

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

相关标签:
22条回答
  • 2020-11-22 09:05

    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.

    0 讨论(0)
  • 2020-11-22 09:06

    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)

    0 讨论(0)
  • 2020-11-22 09:09

    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 )

    0 讨论(0)
  • 2020-11-22 09:10

    I had set one field as "Unsigned" and other one not. Once I set both columns to Unsigned it worked.

    0 讨论(0)
  • 2020-11-22 09:11
    • Engine should be the same e.g. InnoDB
    • Datatype should be the same, and with same length. e.g. VARCHAR(20)
    • Collation Columns charset should be the same. e.g. utf8
      Watchout: Even if your tables have same Collation, columns still could have different one.
    • Unique - Foreign key should refer to field that is unique (usually primary key) in the reference table.
    0 讨论(0)
  • 2020-11-22 09:11

    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.

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