添加外键时出现错误1215。帮我解决我没尝试过的问题

时间:2019-10-29 13:07:57

标签: mysql foreign-keys

我试图在两个现有表之间设置外键关系,但由于某种原因而丢失,我不断收到此错误1215。

两个表的相关字段是:

CREATE TABLE `approvals` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_contract` int(11) NOT NULL,
  `id_user` int(11) NOT NULL,
  `lang` varchar(8) NOT NULL,
  `request_ts` datetime NOT NULL,
  `version` int(11) NOT NULL,
  -- more nullable columns here with no indexing/relationships
  PRIMARY KEY (`id`),
  KEY `approval_id_user` (`id_user`),
  KEY `version` (`version`,`lang`,`id_contract`),
  CONSTRAINT `approval_id_user` FOREIGN KEY (`id_user`) 
      REFERENCES `users` (`iduser`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1079 DEFAULT CHARSET=utf8
CREATE TABLE `version` (
  `idversion` int(11) NOT NULL,
  `idcontract` int(11) NOT NULL,
  `language` varchar(8) NOT NULL,
  PRIMARY KEY (`idversion`,`idcontract`,`language`),
  KEY `fk_version_contracts_idx` (`idcontract`),
  CONSTRAINT `fk_kidversion_contracts` FOREIGN KEY (`idcontract`) 
      REFERENCES `contracts` (`id_contract`) 
      ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8

我尝试了什么
我检查的第一件事是持久性:

SELECT * FROM approvals a 
WHERE NOT EXISTS (
    SELECT 1 FROM version v 
    WHERE v.idcontract = a.id_contract AND v.language = a.lang 
        AND v.idversion = a.version);

这导致从701中返回了0行,好吧,从数据pov看我的数据库应该很好。

所以我检查了排序规则,由于某种原因,版本表是latin1 vs utf8_generic_ci,好的,所以我用此表将版本表恢复到utf8。

ALTER TABLE `kidversion` 
COLLATE = utf8_general_ci;

-- and for good measure
ALTER TABLE `kidversion` 
CHANGE COLUMN `language` `language` VARCHAR(8) 
    CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL;

但是在这一点上,尝试创建外键时仍然出现错误:

ALTER TABLE `approvals` 
ADD CONSTRAINT `approval_ibfk_1`
  FOREIGN KEY (`version` , `lang` , `id_contract`)
  REFERENCES `version` (`idversion` , `language` , `idcontract`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

在我执行的每个步骤中,结果都为1215。当然可以,我想念什么..有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

外键(versionlangid_contract)参考versionidversionlanguageidcontract)和主键(idversionidcontractlanguage)不匹配字段必须具有相同的顺序和类型。 “在引用表中,必须有一个索引,其中外键列以相同的顺序列为第一列。” -https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html