SQLException:无法创建表 errno 150/外键
经过一些研究后,当表引擎类型不匹配或外键创建由于某种原因失败时,似乎会出现 errno 150。无论如何,我的创建脚本看起来像这样:
CREATE TABLE IF NOT EXISTS Users
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
fooType INT UNSIGNED NOT NULL DEFAULT 0,
...More columns, nothing special...
PRIMARY KEY (`id`),
CONSTRAINT Users_fooType_fk
FOREIGN KEY (fooType)
REFERENCES FooTypes (id)
ON DELETE CASCADE
) ENGINE = InnoDB#
CREATE TABLE IF NOT EXISTS FooTypes
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
...More columns, nothing special...
PRIMARY KEY (`id`)
) ENGINE = InnoDB#
因此,我的表引擎显式和隐式匹配(我使用的是 MySQL 5.1.49,据我所知,它默认使用 InnoDB)。
所以唯一的区别是 Users.fooType 有一个默认值。这是问题所在吗?如果是的话,我该如何设置默认值?如果不是,有人发现代码还有其他问题吗?抱歉,我不得不稍微混淆它,但是您必须相信我的话,代码的混淆块是正确的/不相关的。
After doing some research, it would seem that errno 150 occurs when either table engine types don't match, or when foreign key creation fails for whatever reason. Anyway, my Create script looks like this:
CREATE TABLE IF NOT EXISTS Users
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
fooType INT UNSIGNED NOT NULL DEFAULT 0,
...More columns, nothing special...
PRIMARY KEY (`id`),
CONSTRAINT Users_fooType_fk
FOREIGN KEY (fooType)
REFERENCES FooTypes (id)
ON DELETE CASCADE
) ENGINE = InnoDB#
CREATE TABLE IF NOT EXISTS FooTypes
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
...More columns, nothing special...
PRIMARY KEY (`id`)
) ENGINE = InnoDB#
So, my table engines match both explicitly and implicitly (I'm using MySQL 5.1.49, which uses InnoDB by default AFAIK).
So the only difference is that Users.fooType has a default. Is that the problem? If it is, how can I set up a default? If it isn't, anybody see anything else wrong with the code? Sorry I had to obfuscate it slightly, but you'll have to take my word for it that the obfuscated chunks of the code are correct/not related.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须在
Users
之前创建表FooTypes
,因为它甚至在FooTypes 之前使用
存在,意味着违反外键约束,即FooTypes
的引用FooTypes(id)
在提供Users(fooType)
其引用之前必须存在。You have to create table
FooTypes
beforeUsers
, as it uses the reference ofFooTypes
even beforeFooTypes
exist, means violation of Foreign Key constraint, that is,FooTypes(id)
must be exist before providingUsers(fooType)
its reference.REFERENCES FooTypes (id)
失败,因为没有找到FooTypes
表,更不用说id
列了。解决方案:
只需在
Users
之前创建FooTypes
表即可REFERENCES FooTypes (id)
fails as noFooTypes
tables found, let aloneid
column.Solution:
Just create the
FooTypes
table beforeUsers