MySQL - 外键约束错误。无法创建外键
MySQL - Error in foreign key constraint. Unable to create Foreign 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.
谁能告诉我,我做错了什么?
user_role.user_id
是 INT UNSIGNED
,但 users.user_id
只是 INT
。它们必须是相同的数据类型。将 user_role.user_id
更改为 INT
,或将 users.user_id
更改为 INT UNSIGNED
。
我在 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.
谁能告诉我,我做错了什么?
user_role.user_id
是 INT UNSIGNED
,但 users.user_id
只是 INT
。它们必须是相同的数据类型。将 user_role.user_id
更改为 INT
,或将 users.user_id
更改为 INT UNSIGNED
。