mysql - 我无法在表中创建外键 - #1005

标签 mysql key innodb

#1005 - 无法创建表“forum.#sql-da8_f”(错误号:150)

当我想对表应用外键约束时,我不断收到此错误。我不知道可能是什么问题。我了解到,需要使用 InnoDB 才能在 Mysql 上使用外键。 Mysql不是默认自带的吗?

顺便说一句,这里

ALTER TABLE boards
ADD FOREIGN KEY (CategoryId)
REFERENCES categories(CategoryId)

编辑: 这是我创建表格的方式

CREATE TABLE IF NOT EXISTS `boards` (
  `BoardId` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `CategoryId` int(11) DEFAULT '0',
  `ChildLevel` int(11) DEFAULT '0',
  `ParentId` int(11) DEFAULT '0',
  `BoardOrder` int(11) DEFAULT '0',
  `LastMessageId` int(11) DEFAULT '0',
  `MessageUpdatedId` int(11) DEFAULT '0',
  `Groups` varchar(255) DEFAULT '',
  `ProfileId` int(11) DEFAULT '0',
  `BoardName` varchar(255) DEFAULT '',
  `BoardDescription` text,
  `NumberOfTopics` int(11) DEFAULT '0',
  `NumberOfPosts` int(11) DEFAULT '0',
  `CountPosts` int(11) DEFAULT '0',
  `HiddenPosts` int(11) DEFAULT '0',
  `HiddenTopics` int(11) DEFAULT '0',
  PRIMARY KEY (`BoardId`),
  UNIQUE KEY `BoardId` (`BoardId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

这是我的“类别”表:

CREATE TABLE IF NOT EXISTS `categories` (
  `CategoryId` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `CategoryOrder` int(11) DEFAULT '0',
  `CategoryName` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`CategoryId`),
  UNIQUE KEY `CategoryId` (`CategoryId`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=56 ;

最佳答案

问题是,类型不匹配:categories 上的主键是 bigint unsigned,而 boards 上的外键> 是 int 类型。例如。更改 boards 表:

CREATE TABLE IF NOT EXISTS `boards` (
  `BoardId` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `CategoryId` bigint(20) unsigned DEFAULT '0',
  -- ...
)

See this demo.

关于mysql - 我无法在表中创建外键 - #1005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16221455/

相关文章:

mysql - 意外锁定具有主键和唯一键的表

php - Mysql按索引顺序查询

mysql - 在 php 中将表单数据从用户传输到我网站的数据库服务器

python - 使用 sqlalchemy 的复合键关系

api - Google map API - V2 键 x V3 无键

mysql - Insert..Select into InnoDB table with commit after every insert?

php - Android如何实现向PHP-MySQL发送数据?

mysql - SQLSTATE[23000] : Integrity constraint violation: 1062 Duplicate entry '7775-683756' for key 'camera_from_to_unique'

Swift 3.1 - .set Values For Keys 和 Firebase 无法检索用户

MySQL InnoDB 性能问题