Search code examples
mysqlforeign-keysmysql-error-1452

MySQL Error 1452 - can't insert data


I am inserting some data into the following MySQL tables:

CREATE TABLE genotype
(
Genotype VARCHAR(20),
Fitness FLOAT NULL,
Tally INT NULL,
PRIMARY KEY (Genotype)
)ENGINE=InnoDB;


CREATE TABLE gene
(
Gene VARCHAR(20),
E FLOAT NOT NULL,
Q2 FLOAT NOT NULL, 
PRIMARY KEY (Gene)
)ENGINE=InnoDB;

CREATE TABLE genotypegene
(
Genotype VARCHAR(20),
Gene VARCHAR(20),
FOREIGN KEY (Genotype) REFERENCES genotype(Genotype),
FOREIGN KEY (Gene) REFERENCES gene(Gene)
)ENGINE=InnoDB;

I inserted the data into genotype/gene first, but get the following error when trying to insert into genotypegene:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`populationdb`.`genotypegene`, CONSTRAINT `genotypegene_ibfk_2` FOREIGN KEY (`Gene`) REFERENCES `gene` (`Gene`))

The data I'm inserting is into this table is: Genotype1,Gene1 Genotype1,Gene2 Genotype1,Gene3 Genotype1,Gene4

There is one copy of Genotype1 in the genotype table, the idea being that each genotype can contain many genes, but each gene can exist in multiple genotypes (at the moment, there is only 1 genotype, but later I will insert more). I read here that I could turn off Foreign Key Checks, but I am reluctant to do so without knowing the reason for this error. Is this because there is only one copy of Genotype1 in the genotype table? (I have checked that Genotype1, Gene1 etc. are in the same format/spelling in their primary key tables).

Just in case, here is the code I am using to insert the data:

 mysql> LOAD DATA LOCAL INFILE 'C:\\.....genotypegene.csv'
   -> INTO TABLE genotypegene
   -> FIELDS TERMINATED BY ','
   -> (Genotype, Gene);

Thanks


Solution

  • One approach to find out what is causing this would be to do the following:

    Disable Foreign Keys

    SET FOREIGN_KEY_CHECKS = 0;
    

    Load The Data

    Do this using your command:

    mysql> LOAD DATA LOCAL INFILE 'C:\\.....genotypegene.csv'
        -> INTO TABLE genotypegene
        -> FIELDS TERMINATED BY ','
        -> (Genotype, Gene);
    

    Find Orphaned Data

    select gtg.* from genotypegene gtg
    where (gtg.Gene not in (select g.Gene from gene g) 
        or gtg.Genotype not in (select gt.Genotype from genotype gt));
    

    This should give you a list of those rows that are causing your FK constraint violation.

    Fix The Orphaned Data

    Update them? Delete them? Fix them in the CSV? Insert parent row into Gene table? Do whatever is appropriate.

    Enable FK Checks

    SET FOREIGN_KEY_CHECKS = 1;
    

    If nothing else this should give you a clue as to why your are getting the FK constraint violation error.

    Good luck!