Mysql 报错:Cannot add or update a child row: a foreign key constraint fails

错误信息:

insert into student (id,name,age,tid) VALUES ( 1,'张三',18,1)
> 1452 - Cannot add or update a child row: a foreign key constraint fails (`db123`.`student`, CONSTRAINT `tid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`))
> 时间: 0.12s

表结构:

student

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `tid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `tid` (`tid`),
  CONSTRAINT `tid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Mysql 报错:Cannot add or update a child row: a foreign key constraint fails_第1张图片

teacher

CREATE TABLE `teacher` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Mysql 报错:Cannot add or update a child row: a foreign key constraint fails_第2张图片

student表中的tidteacher表中id的外键

再次看下错误信息

insert into student (id,name,age,tid) VALUES ( 1,'张三',18,1)
> 1452 - Cannot add or update a child row: a foreign key constraint fails (`db123`.`student`, CONSTRAINT `tid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`))
> 时间: 0.12s

翻译下来:不能添加或修改子行,外键约束失败

报错原因:

说白了就是:主表teacher中没有id1的数据,所以子表student中就不能添加或修改tid1的数据。

解决方案:

主表teacher中添加id1的数据,即可。

insert into teacher (id,name,age) VALUES(1,'李老师',30)

Mysql 报错:Cannot add or update a child row: a foreign key constraint fails_第3张图片

再次执行insert into student (id,name,age,tid) VALUES ( 1,'张三',18,1)
Mysql 报错:Cannot add or update a child row: a foreign key constraint fails_第4张图片
问题解决。

你可能感兴趣的:(Mysql)