我正在尝试通过 mysql workbench 创建一个表。我收到以下错误:-
错误 1215:无法添加外键约束 SQL 语句:
CREATE TABLE `propman`.`imageadassociation` (
`ImageId` INT NOT NULL,
`AdId` INT NOT NULL,
INDEX `imageId_adassociation_idx` (`ImageId` ASC),
INDEX `adId_adassociation_idx` (`AdId` ASC),
CONSTRAINT `imageId_adassociation`
FOREIGN KEY (`ImageId`)
REFERENCES `propman`.`imagelocation` (`ImageId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `adId_adassociation`
FOREIGN KEY (`AdId`)
REFERENCES `propman`.`advertisement` (`AdId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
imageLocation表创建状态语句如下:-
CREATE TABLE `imagelocation` (
`ImageId` int(11) NOT NULL,
`ImageLocationcol` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
广告表创建语句如下:-
CREATE TABLE `advertisement` (
`AdId` int(10) NOT NULL AUTO_INCREMENT,
`PropertyId` int(10) NOT NULL,
`AdTemplateId` int(10) NOT NULL,
`ValidFrom` date DEFAULT NULL,
`ValidTo` date DEFAULT NULL,
PRIMARY KEY (`AdId`),
KEY `AdTemplateId` (`AdTemplateId`),
CONSTRAINT `advertisement_ibfk_2` FOREIGN KEY (`AdTemplateId`) REFERENCES `adtemplate` (`AdTemplateId`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
最佳答案
imageadassociation
是引用 表。表 imagelocation
和 advertisement
是引用表。
被引用的2列需要满足条件:
来自 Using Foreign Key Constraints 上的 Mysql 手册页:
Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.
并且它们需要在引用 表中有最左边的索引。不满足这些条件。
特别是 imageId
显示宽度并不重要(即:int(11))
关于mysql - 无法在 mysql-workbench 上添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34059826/