MySQL cannot create foreign key constraint

后端 未结 12 2146
夕颜
夕颜 2020-12-08 12:39

I\'m having some problems creating a foreign key to an existing table in a mysql database.

I have the table exp:

+-------------+--------         


        
相关标签:
12条回答
  • 2020-12-08 13:18

    For me it was just the charset and collation of the DB. I changed to utf8_unicode_ci and works

    0 讨论(0)
  • 2020-12-08 13:21

    In my case was created using integer for the id, and the referencing table was creating by default a foreign key using bigint.

    This caused a big nightmare in my Rails app as the migration failed but the fields were actually created in DB, so they showed up in the DB but not in the schema of the Rails app.

    0 讨论(0)
  • 2020-12-08 13:22

    Mine was a collation issue between the referenced table and the to be created table so I had to explicitly set the collation type of the key I was referencing.

    • First I ran a query at referenced table to get its collation type
    show table STATUS like '<table_name_here>';
    
    • Then I copied the collation type and explicitly stated employee_id's collation type at the creation query. In my case it was utf8_general_ci
    CREATE TABLE dbo.sample_db
    (
      id INT PRIMARY KEY AUTO_INCREMENT,
      event_id INT SIGNED NOT NULL,
      employee_id varchar(45) COLLATE utf8_general_ci NOT NULL,
      event_date_time DATETIME,
      CONSTRAINT sample_db_event_event_id_fk FOREIGN KEY (event_id) REFERENCES event (event_id),
      CONSTRAINT sample_db_employee_employee_id_fk FOREIGN KEY (employee_id) REFERENCES employee (employee_id)
    );
    
    0 讨论(0)
  • 2020-12-08 13:25

    In some cases, I had to make the referenced field unique on top of defining it as the primary key.

    But I found that not defining it as unique doesn't create a problem in every case. I have not been able to figure out the scenarios though. Probably something to do with nullable definition.

    0 讨论(0)
  • 2020-12-08 13:27

    Referencing the same column more than once in the same constraint also produces this Cannot find an index in the referenced table error, but can be difficult to spot on large tables. Split up the constraints and it will work as expected.

    0 讨论(0)
  • 2020-12-08 13:29

    I had this error as well. None of the answers pertained to me. In my case, my GUI automatically creates a table with a primary unique identifier as "unassigned". This fails when I try and create a foreign key and gives me the exact same error. My primary key needs to be assigned.

    If you write the SQL itself like so id int unique auto_increment then you don't have this issue but for some reason my GUI does this instead id int unassigned unique auto_increment.

    Hope this helps someone else down the road.

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