我的 mysql 数据库有 parent_table
utf-8 和 2 列(id varchar(14) , name varchar(256))
然后我为这个由 2 列组成的表创建了一个主键,但我必须创建它的长度限制为 200,-因为最大索引长度问题-像这样
alter table parent_table add primary key(id,name (200));
一切都很好,直到我开始创建一个新的 child_table
外键引用父表,子表有 2 列(child_id varchar(14),child_name varchar(256))
注意:两个表是相同的编码(utf-8)、相同的引擎、相同的数据类型、相同的长度 尽管每当我尝试创建外键时
alter table child_table add foreign key test_foreign_key (child_id,
child_name) references parent_table (id, name);
我总是得到一个错误
Error Code: 1005. Can't create table
mci
.#sql-1724_3
(errno: 150 "Foreign key constraint is incorrectly formed")
然后,当我删除 parent_table
中的主键并将 parent_table
和 child_table
中的名称列修改为 varchar(200)然后在 parent_table
中创建主键,通常没有限制,如:
alter table parent_table add primary key(id,name);
然后当我在 child_table
中创建外键时,它起作用了!!!
不幸的是,我无法在我的真实数据库中将名称列长度更改为 200,因为它已经塞满了更长的数据。
我如何在 child_table
中创建一个外键,该外键引用 parent_table
中的复合(2 列)主键,索引长度有限(200 )? 我可以做这样的事情吗..
alter table child_table add foreign key test_foreign_key (child_id,
child_name) references parent_table (id, name(200)); // 200
最佳答案
我明白了,针对我的特殊情况的答案是,我不能
MySQL requires indexes on foreign keys and referenced keys so that ...
它还说
Such an index is created on the referencing table automatically if it does not exist
所以在我的案例中发生的事情是,当我尝试创建外键时,mysql 首先尝试在外键列上创建索引,但是它不能因为最大索引长度问题 ,当我试图在 parent_table
上创建主键时发生同样的问题,这迫使我在 parent_table
上创建前缀“有限长度”主键>
alter table parent_table add primary key(id,name (200));
所以,我必须将 parent_table
中的主键更改为另一个不需要前缀索引的更短长度的列,以便让 mysql 有机会创建索引在 child_table
在同一文档中还有一个有趣的注释,说
Index prefixes on foreign key columns are not supported. One consequence of this is that BLOB and TEXT columns cannot be included in a foreign key because indexes on those columns must always include a prefix length
关于mysql - 如何添加引用 "limited length"的 2 列主键的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37357977/