SQLException:无法创建表 errno 150/外键

发布于 2025-01-07 19:05:33 字数 784 浏览 3 评论 0原文

经过一些研究后,当表引擎类型不匹配或外键创建由于某种原因失败时,似乎会出现 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吃颗糖壮壮胆 2025-01-14 19:05:33

您必须在 Users 之前创建表 FooTypes,因为它甚至在 FooTypes 之前使用 FooTypes引用 存在,意味着违反外键约束,即 FooTypes(id) 在提供 Users(fooType) 其引用之前必须存在。

You have to create table FooTypes before Users, as it uses the reference of FooTypes even before FooTypes exist, means violation of Foreign Key constraint, that is, FooTypes(id) must be exist before providing Users(fooType) its reference.

等数载,海棠开 2025-01-14 19:05:33

REFERENCES FooTypes (id) 失败,因为没有找到 FooTypes 表,更不用说 id 列了。

解决方案:
只需在 Users 之前创建 FooTypes 表即可

REFERENCES FooTypes (id) fails as no FooTypes tables found, let alone id column.

Solution:
Just create the FooTypes table before Users

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文