MySql教程

MySQL外键字段为什么必须加索引

本文主要是介绍MySQL外键字段为什么必须加索引,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

外键字段为什么需要索引?主要原因就在于查询性能了。父子表之间在进行外键检查时,需要一条一条每条必查地校验,而且在对父表的SELECT操作时,为了避免产出数据不一致,使用的是一致性锁定读(SELECT …… LOCK IN SHARE MODE),主动加一个阻塞其他修改操作的读锁。如果没有索引,对于大一点的表而言那效率就非常低下了。参考官方文档https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html,有一段具体的说明。

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 thefirst columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint.index_name, if given, is used as described previously.

MySQL需要外键和引用键上的索引,因此外键检查可以快速,而不需要表扫描。在引用表中,必须有一个索引,其中外键列以相同的顺序作为第一个列列出。如果引用表不存在,则自动在引用表上创建这样的索引。如果您创建了另一个可用于强制外键约束的索引,则该索引可能会在稍后被静默地删除。如果给出了Index_name,就像前面描述的那样使用它。

参考资料:

谈谈我对MySQL外键字段必须索引的一些理解_蛙鳜鸡鹳狸猿-CSDN博客

这篇关于MySQL外键字段为什么必须加索引的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!