简体   繁体   中英

Can a foreign key use unique index?

I created a unique index on a column, and then added a foreign key using ALTER TABLE. MySQL added a non-unique index on top of my unique index to the column. Is the non-unique index necessary? Does it speed things up in any way?

Does it speed things up in any way?

First, Indexes do not always speed things up. Indexes are slowing down update, insert and delete statements, because the index has to be updated along with the data.

Second, there are scenarios, where the mysql-optimizer might decide to use a wrong index, and using another Index might be faster.

Is the non-unique index necessary?

No. See also the mysql documentation about YOUR usecase, if you would have done it the other way round:

http://dev.mysql.com/doc/refman/5.6/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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM