2016-08-03 36 views
3

我已经尝试了所有我能想到但我仍然有问题创建表。mySQL:什么阻止我的外键约束?

我有一个用户表的主键username

+---------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------------+-------------+------+-----+---------+-------+ | created_at | datetime | YES | | NULL | | | updated_at | datetime | YES | | NULL | | | username | varchar(50) | NO | PRI | NULL | | | administrator | tinyint(1) | YES | | NULL | | | fullname | text | YES | | NULL | | | description | text | YES | | NULL | | | password | varchar(60) | NO | | NULL | | +---------------+-------------+------+-----+---------+-------+

,我想创建一个新的表是这样的:

CREATE TABLE sessions ( created_at DATETIME, updated_at DATETIME, token VARCHAR(50) NOT NULL, username VARCHAR(50), PRIMARY KEY (token), FOREIGN KEY(username) REFERENCES users (username) );

但我得到一个讨厌的错误:

ERROR 1215 (HY000): Cannot add foreign key constraint

我通常发现这个错误是由pk/fk对的数据类型不匹配造成的,但这次都清楚地显示varchar(50),所以看起来问题在别处。

我也试过这个,以防万一:

CREATE TABLE sessions ( created_at DATETIME, updated_at DATETIME, token VARCHAR(50) NOT NULL, username varchar(50) NOT NULL, #<- ***added not null*** PRIMARY KEY (token), FOREIGN KEY(username) REFERENCES users (username) );

mysql>SHOW ENGINE INNODB STATUS

LATEST FOREIGN KEY ERROR

2016-08-03 15:13:23 a46fcb70 Error in foreign key constraint of table savesdev/sessions: FOREIGN KEY(username) REFERENCES users (username)): 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. See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html for correct foreign key definition.

这似乎错误是在两种情况下提出:

1)当有不匹配(我已排除)

column types in the table and the referenced table do not match for constraint.

2)如果没有合适的索引上引用的列

Cannot find an index in the referenced table where the referenced columns appear as the first columns

我觉得这两个都覆盖,这是怎么回事?

任何人都可以发现我的错误吗?

+0

'show engine innodb status'。大约1/2的转储将成为“最后的外键错误”部分,其中包含详细信息。很可能你有一个字段定义不匹配。 FK关系必须相同,例如varchar(49) - > varchar(50)'是不允许的,但是'varchar(50) - > varchar(50)'是。或者你在一个较旧的mysql上,它不会在FK字段上自动创建索引,而且你还没有在用户名上手动添加一个密钥。 –

+0

也许你的列用户名有不同的字符集,你可以试试这个:ALTER TABLE sessions MODIFY username VARCHAR(50)CHARACTER SET utf8; ALTER TABLE用户MODIFY username VARCHAR(50)CHARACTER SET utf8; –

+0

这是一个好点@elkorchianas,我会看看.. –

回答

3

也许你的用户名的列有不同的字符集,你可以试试这个:

ALTER TABLE sessions MODIFY username VARCHAR(50) CHARACTER SET utf8; 
ALTER TABLE users MODIFY username VARCHAR(50) CHARACTER SET utf8; 

正如@Graeme斯图尔特建议这里是看我们如何检查承租人组数据库/表或列的链接:How do I see what character set a MySQL database/table/column is?

+1

是,这两个字段都是VARCHAR(50),但现有的表具有utf8_general_ci归类,这使得它们不可兼容。我的实际解决方案是使用utf8_general_ci归类为外键列创建新表。 –