gpt4 book ai didi

mysql - 错误 1215 (HY000) : Cannot add foreign key constraint

转载 作者:可可西里 更新时间:2023-11-01 07:52:30 25 4
gpt4 key购买 nike

我有两个表,我想创建一个外键,但我遇到了错误 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.

但看起来一切都很好,我引用的是父级的主键,两列的类型和长度都相同……看不出哪里出了问题。

最佳答案

我遇到了这个问题并使用 desc TABLE; 检查我的表。我发现我试图在相同长度的有符号和无符号 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 主键应始终从零开始。

关于mysql - 错误 1215 (HY000) : Cannot add foreign key constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24554729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com