mysql - 无法在 mysql-workbench 上添加外键约束

标签 mysql sql mysql-workbench

我正在尝试通过 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引用 表。表 imagelocationadvertisement引用表。

被引用的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/

相关文章:

php - 如何从数据库中输出多个结果(如果有的话)?

php - 在php中执行交易查询时出现错误

mysql - 如何使用 DELETE 并保持参照完整性?

mysql - 根据 IF 语句更新另一列

mysql - Mac 上同步 mysql 命令行监视器(10.8)

java - 我应该如何将 Map<String, LinkedList<Object>> 数据存储到数据库表中?

PHP\MySql 查询错误

php - 将类似 IRS 的税务函数转换为 SQL

mysql - 在两台计算机之间移动连接和实例

mysql - 如何导出 MySQL 数据库,用 X'val' 而不是 0xval 十六进制表示法表示二进制数据?