1452 - Cannot add or update a child row

1452 - Cannot add or update a child row: a foreign key constraint fails (``mydb3.emp1, CONSTRAINT emp1_``ibfk_1 FOREIGN KEY (mgr) REFERENCES emp1 (``empno))`

无法添加子行或更新子行:外键约束失败

出现这种报错一般都是由于表与外键取值范围参照表的相关值不匹配。

  1. 可能是定义外键的sql语句出错了,检查一下就能找出错误。
  2. 也可能是外键取值和参考值不匹配
  3. 若是自关联,更新大量数据时的报错

例如以下代码,一次性更新就会报错

create table emp1(
	empno int primary key,
	ename varchar(10),
	job varchar(10),
	mgr int,
	foreign key (mgr) references emp1 (empno),
	hiredate date,
	sal decimal(7,2),
	comm decimal(7,2),
	deptno int,
	foreign key emp1 (deptno) references dept1 (deptno)

);
insert into emp1 values(1001,'甘宁','文员',1013,'2000-12-17',8000.00,null,20);
insert into emp1 values(1002,'黛绮丝','销售员',1006,'2001-02-20',16000.00,3000,30);
insert into emp1 values(1003,'殷天正','销售员',1006,'2001-02-22',12500.00,5000,30);
insert into emp1 values(1004,'刘备','经理',1009,'2001-04-02',29750.00,null,20);
insert into emp1 values(1005,'谢逊','销售员',1006,'2001-09-28',12500.00,14000,30);
insert into emp1 values(1006,'关羽','经理',1009,'2001-05-01',28500.00,null,30);
insert into emp1 values(1007,'张飞','经理',1009,'2001-09-01',24500.00,null,10);
insert into emp1 values(1008,'诸葛亮','分析师',1004,'2007-04-19',30000.00,null,20);
insert into emp1 values(1009,'曾阿牛','董事长',null,'2001-11-17',50000.00,null,10);
insert into emp1 values(1010,'韦一笑','销售员',1006,'2001-09-08',15000.00,0.00,30);
insert into emp1 values(1011,'周涛','文员',1008,'2007-05-23',11000.00,null,20);
insert into emp1 values(1012,'程普','文员',1006,'2001-12-03',9500.00,null,30);
insert into emp1 values(1013,'庞统','分析师',1004,'2001-12-03',30000.00,null,20);
insert into emp1 values(1014,'黄盖','文员',1007,'2002-01-23',13000.00,null,10);
insert into emp1 values(1016,'黄盖','文员',1015,'2002-01-23',13000.00,null,10);


而解决办法:set foreign_key_checks=0;禁用一下外键约束,之后再打开 :set foreign_key_checks=1;

即可。

你可能感兴趣的:(开发语言,mysql)