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

时间:2022-04-27 20:43:58

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:

在做了一些研究之后,似乎当表引擎类型不匹配时,或者外键创建因任何原因而失败时,会发生errno 150。无论如何,我的Create脚本如下所示:

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).

所以,我的表引擎显式和隐式匹配(我使用MySQL 5.1.49,它默认使用InnoDB 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.

所以唯一的区别是Users.fooType有一个默认值。这是问题吗?如果是,我该如何设置默认值?如果不是,任何人都会看到代码有什么问题吗?对不起,我不得不对它进行一些模糊处理,但你必须接受我的说法,即模糊的代码块是正确的/不相关的。

2 个解决方案

#1


2  

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.

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

#2


1  

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

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

Solution:
Just create the FooTypes table before Users

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

#1


2  

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.

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

#2


1  

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

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

Solution:
Just create the FooTypes table before Users

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