2016-08-03 48 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歸類爲外鍵列創建新表。 –