测试时外键插入失败
来源:2-1 店铺注册之Service层的实现
hsbzzhz
2019-08-02 08:42:58
### SQL: INSERT INTO tb_shop(owner_id, area_id, shop_category_id, shop_name, shop_desc, shop_addr, phone, shop_img, priority, create_time, last_edit_time, enable_status, advice) VALUES (?,?,?,?, ?,?,?,?,?, ?,?, ?,?) ### Cause: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`o2o`.`tb_shop`, CONSTRAINT `fk_shop_shopcate` FOREIGN KEY (`shop_category_id`) REFERENCES `tb_shop_category` (`shop_category_id`)) ; SQL []; Cannot add or update a child row: a foreign key constraint fails (`o2o`.`tb_shop`, CONSTRAINT `fk_shop_shopcate` FOREIGN KEY (`shop_category_id`) REFERENCES `tb_shop_category` (`shop_category_id`)); nested exception is java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`o2o`.`tb_shop`, CONSTRAINT `fk_shop_shopcate` FOREIGN KEY (`shop_category_id`) REFERENCES `tb_shop_category` (`shop_category_id`))
请问老师,是不是因为我数据库的表的外键有问题,
DROP TABLE IF EXISTS `tb_shop`; CREATE TABLE `tb_shop` ( `shop_id` int(10) NOT NULL AUTO_INCREMENT, `owner_id` int(10) NOT NULL COMMENT '店铺创建人', `area_id` int(5) DEFAULT NULL, `shop_category_id` int(11) DEFAULT NULL, `shop_name` varchar(256) NOT NULL, `shop_desc` varchar(1024) DEFAULT NULL, `shop_addr` varchar(200) DEFAULT NULL, `phone` varchar(128) DEFAULT NULL, `shop_img` varchar(1024) DEFAULT NULL, `priority` int(3) DEFAULT '0', `create_time` datetime DEFAULT NULL, `last_edit_time` datetime DEFAULT NULL, `enable_status` int(2) NOT NULL DEFAULT '0', `advice` varchar(255) DEFAULT NULL, PRIMARY KEY (`shop_id`), KEY `fk_shop_area` (`area_id`), KEY `fk_shop_profile` (`owner_id`), KEY `fk_shop_shopcate` (`shop_category_id`), CONSTRAINT `fk_shop_area` FOREIGN KEY (`area_id`) REFERENCES `tb_area` (`area_id`), CONSTRAINT `fk_shop_profile` FOREIGN KEY (`owner_id`) REFERENCES `tb_person_info` (`user_id`), CONSTRAINT `fk_shop_shopcate` FOREIGN KEY (`shop_category_id`) REFERENCES `tb_shop_category` (`shop_category_id`) ) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8;

一开始出现问题的时候我把person里面的几条记录删了,重新在数据库了直接创建了一条id为1的记录,然后似乎就出现了死锁
1回答
同学你好,这个和person没有关系呢,有用的报错信息是(老师以其中一个为例,其它外键错误可参考):
Cannot add or update a child row: a foreign key constraint fails (`o2o`.`tb_shop`, CONSTRAINT `fk_shop_shopcate` FOREIGN KEY (`shop_category_id`) REFERENCES `tb_shop_category` (`shop_category_id`));
可以翻译一下,不能新增或更新子列,外键约束异常。因为tb_shop表的shop_category_id依赖于tb_shop_category表的shop_category_id
所以这个异常说的就是往tb_shop插入的数据里没有tb_shop.shop_category_id或者tb_shop.shop_category_id在tb_shop_category表没有找到匹配的shop_category_id,需要先在那边新建
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
相似问题