我有mysql数据库 parent_table
utf-8有2列(id varchar(14),名称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);
我总是得到一个错误
错误代码:1005 . 无法创建表mci . #sql-1724_3(错误号:150“外键约束形成错误”)
然后,当我在 parent_table
中删除主键并将 parent_table
和 child_table
中的name列修改为varchar(200),然后通常无限制地在 parent_table
中创建主键,如:
alter table parent_table add primary key(id,name);
然后当我在 child_table
中创建外键时, it worked!!!
不幸的是,我无法在我的真实数据库中将列名长度更改为200,因为它已经塞满了更长的数据 .
how can I create a foreign key in the child_table that references a composite(2-column) primary key in the parent_table with limited index length(200)? 我可以这样做吗......
alter table child_table add foreign key test_foreign_key (child_id,
child_name) references parent_table (id, name(200)); // 200
1 回答
我知道了,我的具体情况的答案是, I can't
正如documentation所说
它也说
所以在我的情况下发生的事情是,当我尝试创建外键时,mysql首先尝试在外键列上创建索引,但它不能因为最大索引长度问题,同样的问题发生在我试图在
parent_table
上创建主键,这迫使我在parent_table
上创建前缀"limited length"主键所以, I must 将
parent_table
中的主键更改为另一个不需要前缀索引的较短长度列,以使mysql有机会在child_table
中的同一列上创建索引他说,同样的文件中也有一个有趣的说明