ERROR 1215(HY000):无法添加外键约束

时间:2014-07-03 13:15:37

标签: mysql foreign-keys

我有两张桌子,我想创建一个外键,但我有ERROR 1215。 这是表格。

 CREATE TABLE `entities_def` (
  `entityid` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Entity ID',
  `parentid` int(10) unsigned DEFAULT NULL COMMENT 'Parent Entity ID',
  `nick` varchar(255) NOT NULL COMMENT 'Entity Nickname',
  `esid` int(10) unsigned NOT NULL DEFAULT '1' COMMENT 'Entity State ID',
  `rdn` varchar(255) NOT NULL COMMENT 'Entity LDAP Relative Distinguished Name',
  `etype` enum('physical','legal','structural','external','access') CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'physical' COMMENT 'Entity Type',
  `ctime` timestamp NULL DEFAULT NULL COMMENT 'Time of Creation',
  `mtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Time of Last Modification',
  `cby` int(10) unsigned DEFAULT NULL COMMENT 'Created By',
  `mby` int(10) unsigned DEFAULT NULL COMMENT 'Last Modified By',
  `descr` text COMMENT 'Entity Description',
  PRIMARY KEY (`entityid`),
  KEY `i_parentid` (`parentid`),
  KEY `i_nick` (`nick`),
  KEY `i_esid` (`esid`),
  KEY `i_cby` (`cby`),
  KEY `i_mby` (`mby`),
  CONSTRAINT `entities_def_fk_cby` FOREIGN KEY (`cby`) REFERENCES `users` (`uid`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `entities_def_fk_esid` FOREIGN KEY (`esid`) REFERENCES `entities_states` (`esid`) ON UPDATE CASCADE,
  CONSTRAINT `entities_def_fk_mby` FOREIGN KEY (`mby`) REFERENCES `users` (`uid`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `entities_def_fk_parentid` FOREIGN KEY (`parentid`) REFERENCES `entities_def` (`entityid`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COMMENT='Entities' 

第二个:

CREATE TABLE `userdomains` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `accessuserid` int(10) NOT NULL,
  `domainname` char(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Domain Names'

我尝试按如下方式创建外键约束:

alter table userdomains ADD CONSTRAINT userdomains_fk_accessuserid FOREIGN KEY (accessuserid) REFERENCES entities_def (entityid) ;

但错误不会消失。

运行SHOW ENGINE INNODB STATUS\G后我

    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.

但看起来一切都很好,我引用了父母的主键,这两个列的类型和长度都相同......无法解决问题。

2 个答案:

答案 0 :(得分:5)

我遇到了这个问题并使用desc TABLE;来检查我的表格。我发现我试图在一个相同长度的signed和unsigned int之间创建一个FK关系(在我的例子中是bigint(20))。请记住,int是默认签名和未签名的。

看起来你遇到了同样的问题:

userdomains.accessuserid定义为int(10) NOT NULL,

,而

entities_def.entityid定义为int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Entity ID',

这种关系的唯一问题是两个int(10)值是用不同的范围定义的,因此不兼容。

如果我是你,我会将它们定义为无符号。标准行业最佳实践规定AUTO_INCREMENTing主键应始终从零开始。

答案 1 :(得分:2)

运行SHOW ENGINE INNODB STATUS \ G并查看LATEST FOREIGN KEY ERROR部分。

您可以在MySQL 5.7 Reference Manual 14.7.5.15 SHOW ENGINE Syntax了解有关此命令的更多信息。

相关问题