MySQL Creating tables with Foreign Keys giving errno: 150

前端 未结 20 2422
深忆病人
深忆病人 2020-11-21 05:02

I am trying to create a table in MySQL with two foreign keys, which reference the primary keys in 2 other tables, but I am getting an errno: 150 error and it will not create

20条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:14

    Definitely it is not the case but I found this mistake pretty common and unobvious. The target of a FOREIGN KEY could be not PRIMARY KEY. Te answer which become useful for me is:

    A FOREIGN KEY always must be pointed to a PRIMARY KEY true field of other table.

    CREATE TABLE users(
       id INT AUTO_INCREMENT PRIMARY KEY,
       username VARCHAR(40));
    
    CREATE TABLE userroles(
       id INT AUTO_INCREMENT PRIMARY KEY,
       user_id INT NOT NULL,
       FOREIGN KEY(user_id) REFERENCES users(id));
    

提交回复
热议问题