MySQL是否自动索引外键列?


当前回答

对于那些正在寻找5.7文档引用的人:

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. 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.

其他回答

是的,Innodb提供了这个。你可以在foreign key子句后面加上一个外键名称,或者让MySQL为你创建一个名称。MySQL自动创建一个名为foreign_key_name的索引。

CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action

如果你做ALTER TABLE(而不是CREATE TABLE),你不会自动得到索引,至少根据文档(链接是5.1的,但5.5也是一样的):

[…当您使用ALTER table向表添加外键约束时,请记住首先创建所需的索引。

显然,一个索引是自动创建的,就像罗伯特发布的链接中指定的那样。

InnoDB 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. (This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index_name, if given, is used as described previously.

InnoDB和外键约束

这是不可能得到索引键自动使用

ALTER TABLE (NAME OF THE TABLE) ADD INDEX (FOREIGN KEY)

你创建的表的名称,例如photos和外键,例如照相_id。代码应该是这样的

ALTER TABLE photographs ADD INDEX (photograph_id);

对于那些正在寻找5.7文档引用的人:

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. 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.