InnoDB 为什么要为外键列添加索引

Why InnoDB adds index for foreign key column

MySQL 使用 innoDB 引擎向 MySQL 中的列添加外键时自动添加索引。主键足以搜索行,为外键列添加索引如何影响性能。

提前致谢。

MySQL 文档清楚地说明了这背后的原因 here

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist.

有许多典型的联接查询需要根据外键匹配行,数据库必须找到这些行。该索引通常有助于更快地完成此操作。

如果您正在创建外键,则意味着此列将用于连接数据与任何其他表引用的列,因此可以理解,此列需要索引才能更好地连接。

由于这个原因,此功能内置于 mysql 外键概念中。