问题描述
我在为 mysql 数据库中的现有表创建外键时遇到一些问题.
I'm having some problems creating a foreign key to an existing table in a mysql database.
我有表格exp
:
+-------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| EID | varchar(45) | NO | PRI | NULL | |
| Comment | text | YES | | NULL | |
| Initials | varchar(255) | NO | | NULL | |
| ExpDate | date | NO | | NULL | |
| InsertDate | date | NO | | NULL | |
| inserted_by | int(11) unsigned | YES | MUL | NULL | |
+-------------+------------------+------+-----+---------+-------+
并且我不想创建一个名为 sample_df
的新表来引用它,使用以下内容:
and I wan't to create a new table called sample_df
referencing this, using the following:
CREATE TABLE sample_df (
df_id mediumint(5) unsigned AUTO_INCREMENT primary key,
sample_type mediumint(5) unsigned NOT NULL,
df_10 BOOLEAN NOT NULL,
df_100 BOOLEAN NOT NULL,
df_1000 BOOLEAN NOT NULL,
df_above_1000 BOOLEAN NOT NULL,
target INT(11) unsigned NOT NULL,
assay MEDIUMINT(5) unsigned zerofill NOT NULL,
insert_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
inserted_by INT(11) unsigned NOT NULL,
initials varchar(255),
experiment VARCHAR(45),
CONSTRAINT FOREIGN KEY (inserted_by) REFERENCES user (iduser),
CONSTRAINT FOREIGN KEY (target) REFERENCES protein (PID),
CONSTRAINT FOREIGN KEY (sample_type) REFERENCES sample_type (ID),
CONSTRAINT FOREIGN KEY (assay) REFERENCES assays (AID),
CONSTRAINT FOREIGN KEY (experiment) REFERENCES exp (EID)
);
但我收到错误:
ERROR 1215 (HY000): Cannot add foreign key constraint
为了获得更多信息,我做了:
To get some more information I did:
SHOW ENGINE INNODB STATUSG
我从中得到的:
FOREIGN KEY (experiment) REFERENCES exp (EID)
):
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.
对我来说,列类型似乎匹配,因为它们都是 varchar(45).(我也尝试将 experiment
列设置为非空,但这并没有解决它)所以我猜测问题一定是在被引用的表中找不到被引用列作为第一列出现的索引
.但我不太确定这意味着什么,或者如何检查/修复它.有没有人有什么建议?第一列
是什么意思?
To me the column types seem to match, since they are both varchar(45).(I also tried setting the experiment
column to not null, but this didn't fix it) So I guess the problem must be that Cannot find an index in the referenced table where the referenced columns appear as the first columns
. But I'm not quite sure what this means, or how to check/fix it. Does anyone have any suggestions? And what is meant by first columns
?
推荐答案
只是将其放入可能原因的组合中,当引用表列具有相同的类型"但没有相同的签名时,我遇到了这个问题.
Just throwing this into the mix of possible causes, I ran into this when the referencing table column had the same "type" but did not have the same signing.
在我的例子中,被引用的表列是 TINYINT UNSIGNED 而我的引用表列是 TINYINT SIGNED.对齐两列解决了这个问题.
In my case, the referenced table colum was TINYINT UNSIGNED and my referencing table column was TINYINT SIGNED. Aligning both columns solved the issue.
这篇关于MySQL 无法创建外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!