Manjaro Linux 中 MySQL 中的外键格式不正确错误

Foreign key incorrectly formed error in MySQL in Manjaro Linux

"user table"创建成功。每个列和类型都与 "users table." 相同但是当我创建一个名为 "user_role," 的关联 table 时,无法调用 "user table"。我只在将 MySQL 与 MariaDB 一起使用时出现此错误。在 windows 中安装 mysql 并像这样使用就可以了。在不更改 table 名称的情况下,我可以做些什么来使其正确吗?

两个 table 被转储了,因为我忘记了我把原始代码放在哪里了。但我还是一样。

CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`course_id` bigint(20) DEFAULT NULL,
`password` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKj8ce5cjkm11igsffixdxexrr9` (`course_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`course_id` bigint(20) DEFAULT NULL,
`password` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `course_id` (`course_id`),
CONSTRAINT `users_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE SET NULL) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

create table `user_role`(
`id` int auto_increment not null,
`user_id_fk` bigint,
`role_id_fk` int,
primary key (`id`),
foreign key (`user_id_fk`) references `user`(`id`),
foreign key (`role_id_fk`) references `role`(`id`)
);

--> references user(id) 无效,但 references users(id) 有效。有什么办法让它发挥作用吗?还是改个名字?

外键跨用不同引擎(InnoDB 和 MyISAM)定义的表:

create table `user_role`(
`id` int auto_increment not null,
`user_id_fk` bigint(20),   -- matching data types
`role_id_fk` int(11)       -- matching data types
,primary key (`id`) 
,foreign key (`role_id_fk`) references `role`(`id`)
,foreign key (`user_id_fk`) references `user`(`id`)
);

db<>fiddle demo

相关:Why doesn't MySQL's MyISAM engine support Foreign keys?

建议您没有一个 table 名字是另一个名字的复数形式(user vs users);它可能会导致拼写错误。

不要将 MyISAM 用于任何事情。 (除了极少数例外)

如果这是多对多映射 table 请按照 http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

中的提示进行操作