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

时间:2014-10-10 22:56:23

标签: mysql sql database reference foreign-keys

我需要帮助......在创建数据库时,我一直遇到这个错误:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`accident_db`.`participated`, CONSTRAINT `participated_ibfk_2` FOREIGN KEY (`license`) REFERENCES `car` (`license`))

当我尝试插入参与时,问题就出现了。我尝试整个数据库,编码不一致,检查拼写和其他语法错误。

CREATE TABLE person (
  driver_id VARCHAR(9) PRIMARY KEY,
  name VARCHAR(25),
  address VARCHAR(40)
) engine=innodb;

CREATE TABLE car (
  license VARCHAR(8),
  model VARCHAR(15),
  year date,
  PRIMARY KEY(license)
) engine=innodb;


CREATE TABLE accident (
  report_id VARCHAR(6),
  date date,
  location VARCHAR(25),
  PRIMARY KEY(report_id)
) engine=innodb;

CREATE TABLE owns (
  driver_id VARCHAR(9),
  license VARCHAR(8),
  FOREIGN KEY(driver_id) REFERENCES person(driver_id),
  FOREIGN KEY(license) REFERENCES car(license),
  PRIMARY KEY(driver_id, license)
) engine=innodb;

CREATE TABLE participated (
  driver_id VARCHAR(9),
  license VARCHAR(8) ,
  report_id VARCHAR(6),
  damage_amount decimal(10,2),
  FOREIGN KEY(driver_id) REFERENCES person(driver_id),
  FOREIGN KEY(license) REFERENCES car(license),
  FOREIGN KEY(report_id) REFERENCES accident(report_id),
  PRIMARY KEY(driver_id, license,report_id)
) engine=innodb;


    insert into person values('DRIVER001','John Smith','Tech, TN');
    insert into car values('AABB2000','BMW','2001');
    insert into accident values('AR2197','2014-04-08','Cookeville TN');
    insert into owns values('DRIVER001','AABB2000');
    insert into participated values('DRIVER002','AR2197','CCDD3000','1500');

2 个答案:

答案 0 :(得分:1)

注意您的错误消息。

insert into person values('DRIVER001','John Smith','Tech, TN');

您已插入' DRIVER001'。

insert into participated values('DRIVER002','AR2197','CCDD3000','1500');

但是这一行试图引用' DRIVER002'。但是,修复此问题会导致另一个 FK错误。许可证也不存在。

插入行时,列出表后列的最佳做法。按照表格顺序排列它们,这样可以更容易地看到您出错的地方。 (为简洁起见,我们经常在SO答案中省略列列表,并且更容易关注真正的问题。)

以下插入语句应该会成功。如果确实想要从DRIVER002或CCDD3000许可证中插入数据,您需要将这些值插入到" person"和"汽车"第一

insert into participated (driver_id, license, report_id, damage_amount) 
values('DRIVER001','AABB2000','AR2197','1500');

作为一个单独的问题,专栏"年"应该是整数,而不是日期。

CREATE TABLE car (
  license VARCHAR(8),
  model VARCHAR(15),
  year date,
  PRIMARY KEY(license)
) engine=innodb;

整数年的insert语句不同。

insert into car values('AABB2000','BMW','2001');  -- Not this
insert into car values('AABB2000','BMW', 2001);   -- But this

整数年没有引用。

答案 1 :(得分:0)

我希望你知道主键和外键是如何工作的。如果要将数据插入到作为外键的特定字段,它将在其引用表的主键字段中查找相同的数据。如果匹配,则添加。如果它不匹配,则会按照您的说明发生错误。就像Mike Sherrill所说,你应该把它改成

insert into participated (driver_id, license, report_id, damage_amount)
values('DRIVER001','AABB2000','AR2197','1500');