简体   繁体   English

MYSQL外键,无法创建表(errno:150)

[英]MYSQL Foreign Key, Cant create table (errno:150)

I am trying to build the database and tables for my system. 我正在尝试为我的系统构建数据库和表。 But I found that if I don't add the foreign key in the codes. 但是我发现,如果不在代码中添加外键。 There is no error. 没有错误。 I've used many method try to make the codes works, but it still have error. 我使用了很多方法尝试使代码正常工作,但是仍然有错误。

Create table if not exists users_details_one
(
    fname varchar(255),
    lname varchar(255),
    address varchar(255),
    users_email varchar(255),
    users_password varchar(255),
    department varchar(255)
 );

Create table if not exists users_one
(
    users_email varchar(255),
    users_password varchar(255) ,

    FOREIGN KEY (users_email) REFERENCES users_details_one(users_email),

    FOREIGN KEY (users_password) REFERENCES users_details_one(users_password)   
);

There's a typo in your foreign key: 您的外键中有一个错字:
FOREIGN KEY (users_password) REFERENCES users_details_one(users_spassword) should be FOREIGN KEY (users_password) REFERENCES users_details_one(users_password) FOREIGN KEY (users_password) REFERENCES users_details_one(users_spassword)应该是FOREIGN KEY (users_password) REFERENCES users_details_one(users_password)

and you also need indexes on users_email and users_password in table users_details_one , such as this: 并且您还需要在表users_details_one users_emailusers_password上的users_details_one ,例如:

Create table if not exists users_details_one
(
    fname varchar(255),
    lname varchar(255),
    address varchar(255),
    users_email varchar(255),
    users_password varchar(255),
    department varchar(255),
    index (users_email),
    index (users_password)
 );

Create table if not exists users_one
(
    users_email varchar(255),
    users_password varchar(255) ,

    FOREIGN KEY (users_email) REFERENCES users_details_one(users_email),

    FOREIGN KEY (users_password) REFERENCES users_details_one(users_password)   
);

it is not necessary for the index to be unique. 索引不必唯一。

from the manual 从手册

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. MySQL需要在外键和引用键上建立索引,以便外键检查可以快速进行,而无需进行表扫描。 In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. 在引用表中,必须有一个索引,其中外键列以相同的顺序列为第一列。 Such an index is created on the referencing table automatically if it does not exist. 如果这样的索引不存在,则会在引用表上自动创建。

如果要使列作为外键,则这些列必须是主键,或者必须具有唯一性约束,即在您的情况下,users_details_one的users_email和users_password必须是唯一键或主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM