简体   繁体   中英

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)

and you also need indexes on users_email and users_password in table users_details_one , such as this:

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. 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必须是唯一键或主键。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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