为什么MySQL不允许这个外键?

为什么MySQL不允许这个外键?,mysql,Mysql,我正在使用MySQL 5尝试创建两个表。以下是两张表格: DROP TABLE IF EXISTS `users` ; CREATE TABLE IF NOT EXISTS `users` ( `username` VARCHAR(50) not null , `password` VARCHAR(50) not null, `enabled` boolean not null, `accountNonExpired` boolean not null, `

我正在使用MySQL 5尝试创建两个表。以下是两张表格:

DROP TABLE IF EXISTS  `users` ; 
CREATE TABLE IF NOT EXISTS  `users` (
  `username` VARCHAR(50) not null ,
  `password` VARCHAR(50) not null,      
  `enabled` boolean not null,
  `accountNonExpired` boolean not null,
  `accountNonLocked` boolean not null,
  `credentialsNonExpired` boolean not null, 
  PRIMARY KEY (`username`)
  ) ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;


DROP TABLE IF EXISTS  `authorities` ;
create table IF NOT EXISTS `authorities` (
`username` VARCHAR(50) not null ,
`authority` varchar(50) not null,
foreign key (`username`) references `users` (`username`),
unique index authorities_idx_1 (username, authority)
) engine = InnoDb;
当我尝试执行此语句时,将创建users表,但随后出现错误:

 Error Code: 1005 
 Can't create table 'dental.authorities' (errno: 150)

我不明白为什么当两个引用的列相同时,外键会失败。是否有

根据您的服务器版本和设置,您可能需要添加

DEFAULT CHARACTER SET = utf8

为“authorities”创建表语句。将与引用表的字符集匹配。

请检查以下几点:

我认为
默认字符集=utf8未提供给第二个表

1. The two tables must be ENGINE=InnoDB. (can be others: ENGINE=MyISAM
    works too)
 2. The two tables must have the same charset.
 3. The PK column(s) in the parent table and the FK column(s) must be
    the same data type.
 4. The PK column(s) in the parent table and the FK column(s), if they
    have a define collation type, must have the same collation type;
 5. If there is data already in the foreign key table, the FK column
    value(s) must match values in the parent table PK columns.
 6. And the child table cannot be a temporary table.

希望这有帮助。

外键要求两个键具有相同的字符集。 加

到第二个表创建指令


编辑:哦,孩子,我参加聚会好像迟到了。

这对我来说很成功:而且看起来很好。您使用的是什么MySQL版本?(只要先创建
用户
),为什么要使用varchar外键而不是if?使用varchar字段作为主键是一个错误的ideiadid。您可以查看类似问题的注释:@demonofnight:varchar主键本质上没有“错误”。或者使用decimal、char、float、date或timestamp主键。“can-be-others:ENGINE=MyISAM-works-too”谢谢benfranke,我认为只有列数据类型必须匹配。
DEFAULT CHARACTER SET = utf8;