mysql foreign key error #1452

后端 未结 4 1605
北荒
北荒 2020-12-18 05:38
ALTER TABLE  `groups` ADD FOREIGN KEY (  `company_id` ) REFERENCES  `summaries`.`companies` (

`id`
) ON DELETE CASCADE ;

MySQL said: 

#1452 - Cannot add or update         


        
4条回答
  •  猫巷女王i
    2020-12-18 06:06

    I just had this problem, although in a somewhat more specific scenario.

    In my case, I had added, to an existing table, a column that I needed to be both nullable and act as a foreign key (i.e., for non-null entries to be bound by a foreign key constraint).

    The referenced column looked like this:

    +-------------+-------------+------+-----+---------+----------------+
    | Field       | Type        | Null | Key | Default | Extra          |
    +-------------+-------------+------+-----+---------+----------------+
    | id          | int(10)     | NO   | PRI | NULL    | auto_increment |
    +-------------+-------------+------+-----+---------+----------------+
    

    and the referencing one like this:

    +-------------+-------------+------+-----+---------+----------------+
    | Field       | Type        | Null | Key | Default | Extra          |
    +-------------+-------------+------+-----+---------+----------------+
    | bed_id      | int(10)     | YES  |     | NULL    |                |
    +-------------+-------------+------+-----+---------+----------------+
    

    Turned out that I had forgotten to specify DEFAULT NULL when adding the referencing column to the existing table and so it was automatically filled with zeros, which failed the foreign key constraint.

    I changed them to NULL:

    update devices set bed_id = NULL where bed_id = 0;
    

    and then successfully added the foreign key constraint. Hope this helps someone

提交回复
热议问题