MySQL InnoDB 外键问题

标签 mysql foreign-keys innodb errno

我有下面的表,我试图在 MySQL 中运行它们,但我不断收到 errno 150。只是不知道为什么,但 MySQL 似乎无法创建外键约束。我已经查看了 InnoDB 设置 FK 的规则,一切似乎都正常。有人可以借我另一双眼睛和专业知识吗?

-- Table publication_type (parent table)
CREATE TABLE publication_type (
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  publication_type varchar(55)  NOT NULL,
  tstamp timestamp  NOT NULL  DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT publication_type_pk PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

-- Table publication (child table)
CREATE TABLE publication (
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  authors varchar(255)  NOT NULL,
  publication_title varchar(100)  NOT NULL,
  publication_type_id int(11) UNSIGNED NOT NULL,
  user_id int(11) UNSIGNED NOT NULL,
  CONSTRAINT publication_pk PRIMARY KEY (id),
  CONSTRAINT publication_type_fk FOREIGN KEY (publication_type_id)  REFERENCES publication_type(id) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

最佳答案

类型不匹配:

publication_type.id 的类型为 int UNSIGNED

publication.publication_type_id 的类型为 int

另请参阅文档:http://dev.mysql.com/doc/refman/5.1/en/create-table-foreign-keys.html ,具体来说:

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.

强调我的。

关于MySQL InnoDB 外键问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32590881/

相关文章:

mysql - 级联删除数据库记录到删除相关图像文件

php - fatal error : Uncaught Error: Cannot use object of type mysqli_result as array with databases

mysql - 似乎无法将 MySQL 查询转换为 Laravel 查询生成器

php - Laravel whereHas to realted model,whereHas to that related modal not working

php - 在我的表中创建 message_id 时出现 MySQL 错误

mysql - 插入导致 InnoDB 中出现死锁。这怎么发生的?

mysql - 在一个查询中使用 INSERT、SELECT 和 UPDATE?

mysql - mysql建表

mysql - 使用外键插入数据并避免重复

mysql - 没有 InnoDB 的 Magento