我正在尝试将带有棒球时间表的.csv文件加载到游戏表中。csv文件的内容如下所示:
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
我尝试插入它们的sql语句是:
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');
但是我得到了错误:
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`))
哦,这是游戏桌的描述:
+---------------+-------------+------+-----+---------+----------------+ | 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 | | +---------------+-------------+------+-----+---------+----------------+
您可以通过set foreign_key_checks = 0;在输入之前使用来禁用外键检查(请确保SET foreign_key_checks = 1;在运行后使用来将其设置回原来的状态。
set foreign_key_checks = 0;
SET foreign_key_checks = 1;
你真正应该做的是确保,无论表hometeam_id,并awayteam_id都指向 HAVE 要插入的值。如果团队表正在以与您的游戏表相同的CSV格式插入数据,请先执行团队表,但实际情况并非如此。
hometeam_id
awayteam_id
最后,你可以卸下hometeam_id和awayteam_id外键,稍后再添加他们这样的例子: ALTER TABLE table_name DROPFOREIGN KEY table_name_ibfk_1;
ALTER TABLE table_name DROPFOREIGN KEY table_name_ibfk_1