无法添加或更新子行:外键约束失败(`dbName`。#sql-e77_7`

时间:2016-05-18 07:02:01

标签: mysql sql foreign-key-relationship

我正在尝试向表中添加一列并将其索引到另一列。执行迁移时,会抛出错误:

Cannot add or update a child row: a foreign key constraint fails (`dbName`.`#sql-e77_7`, CONSTRAINT `fkName` FOREIGN KEY (`column`) REFERENCES `targetTable` (`targetColumn`) ON DELETE CASCADE ON UPDATE CASC)

有人能解释一下“#sql-e77_7”是如何生成的?

1 个答案:

答案 0 :(得分:1)

如果未找到父级,则无法添加或更新行,应插入包含父级的行,然后插入子级。

这是一个例子 我有两个表exercice和exercice_entite

CREATE TABLE exercice
(
  exercice_id serial NOT NULL,
  date_debut date,
  date_fin date,
  exercice_etat text,
  exercice_code text,
  CONSTRAINT exercice_pkey PRIMARY KEY (exercice_id)
)

CREATE TABLE exercice_entite
(
  id_exercice_entite serial NOT NULL,
  id_exercice_pere integer,
  code_entite_filiale character varying(10),
  etat_exercice_entite text,
  code_exercice_entite text,
  code_entite_mm character varying(10),
  CONSTRAINT exercice_entite_pkey PRIMARY KEY (id_exercice_entite),
  CONSTRAINT exercice_entite_code_entite_filiale_fkey FOREIGN KEY (code_entite_filiale)
      REFERENCES entite_filiale (code_entite_filiale) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT exercice_entite_code_entite_mm_fkey FOREIGN KEY (code_entite_mm)
      REFERENCES entite_mm (code_entite) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT exercice_entite_id_exercice_pere_fkey FOREIGN KEY (id_exercice_pere)
      REFERENCES exercice (exercice_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

在这个示例中,父表是exercice,子表是exercice_entite,因为表exercice_entite中的每一行都有一个引用表exercice的外键id_exercice_pere。

在exercice_entite mysql中插入新行之前检查exercice中是否有一行,其中exercice_id等于插入行中id_exercice_pere的值