MySQL Cannot Add Foreign Key Constraint

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

    Confirm that the character encoding and collation for the two tables is the same.

    In my own case, one of the tables was using utf8 and the other was using latin1.

    I had another case where the encoding was the same but the collation different. One utf8_general_ci the other utf8_unicode_ci

    You can run this command to set the encoding and collation for a table.

    ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    

    I hope this helps someone.

    0 讨论(0)
  • 2020-11-22 08:58

    Check the signing on both your table columns. If the referring table column is SIGNED, the referenced table column should be SIGNED too.

    0 讨论(0)
  • 2020-11-22 08:59

    I had a similar error in creating foreign key in a Many to Many table where the primary key consisted of 2 foreign keys and another normal column. I fixed the issue by correcting the referenced table name i.e. company, as shown in the corrected code below:

    create table company_life_cycle__history -- (M-M)
    (
    company_life_cycle_id tinyint unsigned not null,
    Foreign Key (company_life_cycle_id) references company_life_cycle(id) ON DELETE    CASCADE ON UPDATE CASCADE,
    company_id MEDIUMINT unsigned not null,
    Foreign Key (company_id) references company(id) ON DELETE CASCADE ON UPDATE CASCADE,
    activity_on date NOT NULL,
    PRIMARY KEY pk_company_life_cycle_history (company_life_cycle_id, company_id,activity_on),
    created_on datetime DEFAULT NULL,
    updated_on datetime DEFAULT NULL,
    created_by varchar(50) DEFAULT NULL,
    updated_by varchar(50) DEFAULT NULL
    );
    
    0 讨论(0)
  • 2020-11-22 09:02

    I faced the issue and was able to resolve it by making sure that the data types were exactly matching .

    I was using SequelPro for adding the constraint and it was making the primary key as unsigned by default .

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

    My problem was that I was trying to create the relation table before other tables!

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

    One additional cause of this error is when your tables or columns contain reserved keywords:

    Sometimes one does forget these.

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