MySQL .csv load failing due to “Cannot add or update a child row: foreign key constraint fails”

你说的曾经没有我的故事 提交于 2019-12-10 21:19:24

问题


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    |                |
+---------------+-------------+------+-----+---------+----------------+

回答1:


You can disable foreign key checks by using set foreign_key_checks = 0; before the input (make sure to set it back using SET foreign_key_checks = 1; after the run.

What you really should do is make sure that whatever table hometeam_id and awayteam_id are 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;




回答2:


You should disable foreigh keys check

SET foreign_key_checks = 0;

and switch it back after the import

SET foreign_key_checks = 1;

And be careful with that option ;)

MySQL – Disable Foreign Key Checks or Constraints



来源:https://stackoverflow.com/questions/6470450/mysql-csv-load-failing-due-to-cannot-add-or-update-a-child-row-foreign-key-co

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!