MySQL. Can't create table errno 150

前端 未结 22 1152
广开言路
广开言路 2020-12-01 09:59

I have to create a database with two tables in MySQL, but the script fails with errno 150 (foreign key problem). I double-checked the foreign key fields to be the same on bo

相关标签:
22条回答
  • 2020-12-01 10:46

    An option (depending on the case) would be to disable the MySQL integrity check:

    SET FOREIGN_KEY_CHECKS = 0;
    
    0 讨论(0)
  • 2020-12-01 10:46

    You also may encounter the same error when attempting to reference a composite key in your foreign key.

    For example:

    CREATE TABLE `article` (
      `id` int(10) unsigned NOT NULL,
      `type` enum('X','Y','Z') NOT NULL,
      PRIMARY KEY (`id`,`type`)
    ) ENGINE InnoDB;
    
    CREATE TABLE `t1` (
      `user_id` int(10) unsigned NOT NULL,
      `type` enum('X','Y','Z') NOT NULL,
      `article_id` int(10) unsigned NOT NULL,
      CONSTRAINT `user_access_article_ibfk_2` FOREIGN KEY (`article_id`, `type`) REFERENCES `article` (`id`, `type`) ON DELETE CASCADE ON UPDATE CASCADE
    ) ENGINE=InnoDB
    

    In this case, it is important to use article_id and type field in the FK definition in the very same order as they appear in the article table PRIMARY KEY definition.

    0 讨论(0)
  • 2020-12-01 10:48

    I had a similar error on one of my tables. When checked column Collation was different, which worked once changed both columns to the same Collation type.

    After reading most of the suggested solution here. I just thought it might be helpful if I just list down all the possibilities which could throw this error.

    1, Check CASE of the Column 2, Check COLLATION of Columns 3, Check if there is a key created in both tables for the column (Unique, Primary)

    0 讨论(0)
  • 2020-12-01 10:51

    One of the answers here suggests to disable the foreign key integrity check. This is a BAD idea. There are two likely culprits here:

    • Data type mismatch between referenced primary key and referencing foreign key
    • Indices. Any foreign keys which you index must be NOT NULL
    0 讨论(0)
  • Depending on the version of MySQL you may need to create an index on table1.field1 first.

    0 讨论(0)
  • 2020-12-01 10:53

    In my case was probably a server bug dropping a table with the same name. Dropping the whole shcema and re-creating it solved the problem.

    0 讨论(0)
提交回复
热议问题