【发布时间】:2014-02-26 20:41:28
【问题描述】:
我在为 mysql 数据库中的现有表创建外键时遇到一些问题。
我有桌子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 的新表来引用它,使用以下内容:
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
为了获得更多信息,我做了:
SHOW ENGINE INNODB STATUS\G
我从中得到的:
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 列设置为不为空,但这并没有解决它)所以我想问题一定是那Cannot find an index in the referenced table where the referenced columns appear as the first columns。但我不太确定这意味着什么,或者如何检查/修复它。有没有人有什么建议? first columns是什么意思?
【问题讨论】:
-
在任何答案或问题中,我都没有发现由于字符集的差异而可能发生此错误。谢谢..干杯!!!
-
另外,请仔细检查您的列排序规则。您的表格可以是 utf8mb4,但该列可以有不同的排序规则!
-
@Watson 字符集在我的情况下,但你得到了我的支持让我思考。
标签: mysql indexing foreign-keys