首页 文章

如何添加引用2列主键的外键“有限长度”

提问于
浏览
2

我有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_tablechild_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 回答

  • 0

    我知道了,我的具体情况的答案是, I can't

    正如documentation所说

    MySQL需要外键和引用键的索引,以便......

    它也说

    如果引用表不存在,则会自动在引用表上创建此索引

    所以在我的情况下发生的事情是,当我尝试创建外键时,mysql首先尝试在外键列上创建索引,但它不能因为最大索引长度问题,同样的问题发生在我试图在 parent_table 上创建主键,这迫使我在 parent_table 上创建前缀"limited length"主键

    alter table parent_table add primary key(id,name (200));
    

    所以, I mustparent_table 中的主键更改为另一个不需要前缀索引的较短长度列,以使mysql有机会在 child_table 中的同一列上创建索引

    他说,同样的文件中也有一个有趣的说明

    不支持外键列上的索引前缀 . 这样做的一个结果是BLOB和TEXT列不能包含在外键中,因为这些列上的索引必须始终包含前缀长度

相关问题