MySQL Cannot Add Foreign Key Constraint

后端 未结 22 1821
时光取名叫无心
时光取名叫无心 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:12

    I had this same issue then i corrected the Engine name as Innodb in both parent and child tables and corrected the reference field name FOREIGN KEY (c_id) REFERENCES x9o_parent_table(c_id)
    then it works fine and the tables are installed correctly. This will be use full for someone.

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

    Try to use the same type of your primary keys - int(11) - on the foreign keys - smallint(5) - as well.

    Hope it helps!

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

    My solution is maybe a little embarrassing and tells the tale of why you should sometimes look at what you have in front of you instead of these posts :)

    I had ran a forward engineer before, which failed, so that meant that my database already had a few tables, then i have been sitting trying to fix foreign key contraints failures trying to make sure that everything was perfect, but it ran up against the tables previously created, so it was to no prevail.

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

    I got the same error. The cause in my case was:

    1. I created a backup of a database via phpmyadmin by copying the whole database.
    2. I created a new db with the same name the old db had und selected it.
    3. I started an SQL script to create updated tables and data.
    4. I got the error. Also when I disabled foreign_key_checks. Altough the database was completely empty.

    The cause was: Since i used phpmyadmin to create some foreign keys in the renamed database - the foreign keys where created with a database name prefix but the database name prefix was not updated. So there were still references in the backup-db pointing to the newly created db.

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