简体   繁体   中英

Cannot add foreign key constraint error in MySQL

In my local environment database(localhost:3306, mysql 5.7.20), everything works fine. but In aws RDS database(mysql 5.7.22), Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint error occur.

full log is below.

Executing (default): 

CREATE TABLE IF NOT EXISTS `folders`
    (`id` CHAR(36) BINARY , `folderName` VARCHAR(255),
     `folderCoverImage` VARCHAR(255), `createdAt` DATETIME NOT NULL,
     `updatedAt` DATETIME NOT NULL, `fk_user_id` CHAR(36) BINARY,
     `fk_category_id` CHAR(36) BINARY,
    PRIMARY KEY (`id`),
    FOREIGN KEY (`fk_user_id`) REFERENCES `users` (`id`)
        ON DELETE CASCADE ON UPDATE RESTRICT,
    FOREIGN KEY (`fk_category_id`) REFERENCES `categories` (`id`)
        ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint

users:

CREATE TABLE IF NOT EXISTS `users` (`id` CHAR(36) BINARY , `username` VARCHAR(255), `email` VARCHAR(255) UNIQUE, `socialProvider` VARCHAR(255), `profileImg` TEXT, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

categories:

 CREATE TABLE IF NOT EXISTS `categories` (`id` CHAR(36) BINARY , `name` VARCHAR(255) UNIQUE, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Executing (default): SHOW INDEX FROM categories

and my node.js code here.

    Folder.associate = function associate () {
  Folder.belongsTo(User, {
    foreignKey: 'fk_user_id',
    onDelete: 'CASCADE',
    onUpdate: 'restrict'
  });
  Folder.hasMany(Work, {
    as: 'Work',
    foreignKey: 'fk_folder_id',
    onDelete: 'CASCADE',
    onUpdate: 'restrict'
  });
  Folder.belongsTo(Category, {
    as: 'Category',
    foreignKey: 'fk_category_id'
  });
};

also, table users, categories, post, tag have existed.

Create table order is here http://sqlfiddle.com/#!9/2162ca

I don't know why it dosn't work at aws RDS.

The problem might be the database is not empty. In such case, when one of the rows does not fulfill foreign key requirement, adding the requirement to the whole table will fail.

Make sure all the rows on the AWS RDS can fulfill the requirement and that their foreign records exist.

Example: let's say you create a table with books and user_id column. You decide that user_id with a value of "0" means no user was assigned to the row (book is still in the library). Then, the code changes and you implement user_id as a foreign key (user_id should now point to "user" table, "id" column which you would normally do via:

ALTER TABLE database.books
  ADD FOREIGN KEY book_user_id(user_id) REFERENCES user(id);

Now, if you already have books in your database with user_id column having "0" value, the query will fail, because there are records that point to non-existing user (with id of "0"). To fix this, you need to update the records with broken soon-to-be reference first. In this particular case, creatng a "librarian" user with some id of ie 123, then doing: UPDATE books set user_id=123 WHERE user_id=0; Would do the trick and allow you to create the foreign key without issue.

Can you check the order of create tables. When you change the order so that table (whose primary key is being referenced) already exists the error willnot occur.

Possible duplicate here

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