gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:53:49 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com