【问题标题】:I can't create a foreign key in my table - #1005我无法在表中创建外键 - #1005
【发布时间】:2013-04-25 17:52:44
【问题描述】:

#1005 - 无法创建表 'forum.#sql-da8_f' (errno: 150)

当我想将外键约束应用于我的表时,我不断收到此错误。我不知道可能是什么问题。我了解到,需要使用 InnoDB 才能在 Mysql 上使用 FOREIGN KEY。不是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 ;

【问题讨论】:

  • 您是如何创建表格的?
  • 请提供更多信息。向我们展示您的架构和/或创建sqlfiddle.com
  • 检查编辑。我添加了我的餐桌信息。
  • 我们还需要categories的架构。

标签: mysql key innodb


【解决方案1】:

问题是类型不匹配: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.

【讨论】:

  • 匹配成功了。我首先将板表上的 CategoryId 更改为 bigint 就像 tha 类别一样,但直到我也将其设为无符号时它才起作用。
猜你喜欢
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-03-30
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 2012-10-07
相关资源
最近更新 更多