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

时间:2013-07-12 11:53:00

标签: 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,
  `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)

当两个引用的列相同时,我没有看到为什么这个外键失败。有吗

3 个答案:

答案 0 :(得分:1)

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

DEFAULT CHARACTER SET = utf8

到“权限”的CREATE TABLE语句。这将匹配引用表的字符集。

答案 1 :(得分:1)

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

DEFAULT CHARACTER SET = utf8;

到第二个表CREATE指令。

编辑:哦,男孩看起来我已经迟到了。

答案 2 :(得分:0)

查看以下几点:

我认为DEFAULT CHARACTER SET = 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.

希望这有帮助。

相关问题