mysql - 如何添加引用 "limited length"的 2 列主键的外键

标签 mysql

我的 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_tablechild_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

最佳答案

我明白了,针对我的特殊情况的答案是,我不能

作为documentation

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/

相关文章:

mysql - hql:内部加入 Map<key,value> 并在选择中访问键和值?

MySQL 三角数学计算距离结果为 null

mysql - 安装 MariaDB 归档引擎

MySQL ENUM 月份输入问题

php - 从单独的列为 MIN() 的列中选择一个 SQL 值

sql - 如何使用存储过程根据传递的运算符 <,= by param 执行查询?

php - sql查询不适用于order by

php - Innodb引擎不支持全文索引,如何进行文本搜索?

mysql - 当没有记录存在时返回一些东西,infobright db

mysql - 如何将 RDS 与 phpmyadmin 连接 - AWS