MySQL-外键约束错误。无法创建外键

时间:2019-08-03 22:20:31

标签: mysql foreign-keys primary-key

我在MySQL中的外键有问题,我真的为它为什么不起作用感到困惑。

我有下表:

CREATE TABLE IF NOT EXISTS users (
    `user_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `username` VARCHAR(30) NOT NULL,
    `email` VARCHAR(50) NOT NULL,
    `password` CHAR(128) NOT NULL
    UNIQUE INDEX unique_user (username, email)
) ENGINE = InnoDB ;

CREATE TABLE IF NOT EXISTS roles (
  role_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  role_name VARCHAR(50) NOT NULL
);

CREATE TABLE IF NOT EXISTS user_role (
  user_id INT(11) UNSIGNED NOT NULL,
  role_id INT(11) UNSIGNED NOT NULL,

  FOREIGN KEY (user_id) REFERENCES users(user_id)
  FOREIGN KEY (role_id) REFERENCES roles(role_id)
) ENGINE=InnoDB;

可以毫无问题地创建role_id的外键,但是user_id出现问题,并且出现以下错误:

Error in foreign key constraint of table user_role: FOREIGN KEY (user_id) REFERENCES users(user_id): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables.

有人能启发我,我做错了吗?

1 个答案:

答案 0 :(得分:1)

user_role.user_idINT UNSIGNED,但是users.user_id只是INT。它们必须是相同的数据类型。将user_role.user_id更改为INT,或将users.user_id更改为INT UNSIGNED