2013-07-12 46 views
0

我正在使用MySQL 5来尝试创建两个表。这里有两个表:为什么MySQL不允许这个外键?

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; 

当我尝试执行该语句,创建用户表,但后来我得到的错误:

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

我没有看到为什么这个外键时失败两个引用的列是相同的。取决于你的服务器版本,并设置有

+0

这为我成功建立:http://sqlfiddle.com/#!2/1e9acf,看起来不错。你使用的是什么MySQL版本? (只要'用户'是首先创建的) –

+0

为什么使用varchar外键而不是if? 使用varchar字段作为主键是一个坏想法 – Lefsler

+0

你检查了类似问题的意见:http://stackoverflow.com/questions/1457305/mysql-creating-tables-with-foreign-keys-giving- errno-150?rq = 1 – Kaffee

回答

1

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

DEFAULT CHARACTER SET = utf8; 

到你的第二张表CREATE指令。

编辑:哦,男孩看起来像我迟到了派对。

+0

谢谢benfranke,我以为只有列数据类型必须匹配。 – sonoerin

1

,你可能需要添加

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

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. 

希望这有助于。

+0

”可以是其他:ENGINE = MyISAM 也可以“< - 错误!你没有收到错误,MyISAM仍然不支持外键 – fancyPants