Search code examples
mysqlforeign-keysmysql-error-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)   
);

Solution

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