MySQL:错误代码:1215。无法添加外键约束

MySQL : Error Code: 1215. Cannot add foreign key constraint

我有两个表:

Table: utenti
Columns:
userId varchar(255) PK 
password varchar(255)

Table: agenzie
Columns:
agenziaId varchar(255) PK 
userId varchar(255)

当我尝试在 agenzie 上创建外键时,出现此错误消息:

ALTER TABLE agenzie ADD FOREIGN KEY (userId) REFERENCES utenti(userId)  Error Code: 1215. Cannot add foreign key constraint 0.015 sec

我该如何解决?

谢谢。

编辑:

DROP TABLE IF EXISTS `utenti`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `utenti` (
`userId` varchar(255) CHARACTER SET latin1 NOT NULL,
`password` varchar(255) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `agenzie`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agenzie` (
`agenziaId` varchar(255) NOT NULL,
`userId` varchar(255) NOT NULL,
PRIMARY KEY (`agenziaId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

你应该可以 运行:

show engine innodb status

并搜索短语 latest foreign key error(可能是大写)。

这应该提供有关为什么约束创建失败的更多详细信息。

当然,鉴于错误消息文本 Error Code: 1215. Cannot add foreign key constraint 完全没有用,您一定想知道为什么开发人员不立即向您提供该信息,而不是强迫您去寻找它.


既然你已经做到了,并且看到了:

2015-02-19 00:51:55 1528 Error in foreign key constraint of table tesoreria/#sql-12a4_bd: FOREIGN KEY (userId) REFERENCES utenti(userId): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables.

这似乎是两件事之一。首先是没有包含 utenti(userId) 的索引,如果它是主键,显然不是这种情况。

第二个是列不匹配,根据您添加的 DDL,这似乎是罪魁祸首,因为这两列定义为:

`userId` varchar(255) CHARACTER SET latin1 NOT NULL,
`userId` varchar(255) NOT NULL,

换句话说,可能是字符集规范的存在使列成为不同的类型。我建议创建它们完全相同的类型,看看是否能解决问题。

非常感谢,我已经能够看到您的说明中的错误,并且看到了来自其他 table (direccion) 的一个外键,它锁定了 [=25= 的创建] (provincia) 因为外键的列类型与引用的 table 的列类型不同(provincia,即将创建)。

创建 (provincia) 的 table 之前被删除,问题已通过 sudo mysqladmin -p flush-tables 解决,指向它的外键在删除后仍然存在。

我已将外键从 direccion 删除到 provincia,然后能够创建 provincia。然后我更改了 direccion 中的列类型并重新创建了外键。