I’m trying to load a .csv file with baseball schedules into a table of games. The csv file contents look like this:
5/17/2011,8:10 PM,14,13,Kansas City,MO
5/18/2011,8:10 PM,14,16,Chicago,IL
5/19/2011,8:10 PM,14,16,Chicago,IL
5/20/2011,7:05 PM,26,14,Columbus,OH
and my sql statement to try and insert them is:
LOAD DATA LOCAL INFILE 'c:/ftpsite/comp.csv' INTO TABLE game
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(@DATE_STR, time, awayteam_id, hometeam_id,locationcity,locationstate)
SET date = STR_TO_DATE(@DATE_STR, '%c/%e/%Y');
But I’m getting the error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`gamelydb`.`game`, CONSTRAINT `hometeam_id_refs_id` FOREIGN KEY (`hometeam_id`) REFERENCES `team` (`id`))
Oh, and here’s the description of the game table:
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| date | date | NO | | NULL | |
| time | time | NO | | NULL | |
| hometeam_id | int(11) | NO | MUL | NULL | |
| awayteam_id | int(11) | NO | MUL | NULL | |
| locationcity | varchar(30) | NO | | NULL | |
| locationstate | varchar(20) | NO | | NULL | |
+---------------+-------------+------+-----+---------+----------------+
You can disable foreign key checks by using
set foreign_key_checks = 0;before the input (make sure to set it back usingSET foreign_key_checks = 1;after the run.What you really should do is make sure that whatever table
hometeam_idandawayteam_idare pointing to HAVE the values you are inserting. If the team tables are getting data inserted into them in the same CSV as your game table, do the team tables first, but that doesn’t look to be the case.Finally, you can remove the foreign keys on the hometeam_id and awayteam_id and add them later like this example:
ALTER TABLE table_name DROP FOREIGN KEY table_name_ibfk_1;