我有两个表,parent
并且child
该表在使用该列的child
表上有一个 FK 。添加此 FK 时,我可以看到该表同时具有 FK 和表示该 FK 的索引。parent
parent_id
child
child
但是当我在包含的表上添加一个唯一约束时,parent_id
我可以看到代表 FK 的索引被替换为新的唯一约束。
前任:
create table parent
(
parent_id int unsigned not null auto_increment primary key
);
create table child
(
child_id int unsigned not null auto_increment primary key,
parent_id int unsigned not null,
age smallint unsigned null,
constraint FK__CHILD__PARENT
foreign key (parent_id) references parent (parent_id)
);
此时我可以看到表上同时FK_CHILD_PARENT
存在一个 FK 和一个名为的索引child
。
现在我添加唯一约束:
alter table child add constraint unique_parentId_age unique (parent_id, age);
我可以看到unique_parentId_age
索引替换了FK__CHILD__PARENT
索引。
我不明白为什么会这样?如果另一个索引已经存在并且以与 FK 相同的列开头,是否不可能有一个表示 FK 的索引。
我正在使用 MySQL 5.7
索引不代表外键约束;它独立于约束而存在并支持其执行。拥有冗余索引在技术上是可能的,但它是不必要的:任何受益于索引 on 的查询
(parent_id)
都可以同样好地由索引 on 支持(parent_id, age)
,并且维护冗余索引不利于性能。这是按设计和记录工作的(强调我的):
如果出于某种原因您坚持使用冗余索引,我想您可以尝试显式创建它并给它一个非默认名称。