Why does mysql automatically add an index for foreign key checks?

areke :

I know that mysql does this, but I don't quite understand why. If you have a child table referencing a parent table, I would understand why an index would be needed on the parent table. When inserting, you have to look up if a row exists in that table.

But why is an index automatically created in the child table? When does mysql use this index?

Barmar :

If you use options like ON DELETE CASCADE and ON DELETE SET NULL, all the related child rows have to be found, and indexes are needed to make this efficient.

Even if you don't use these options, checking foreign keys requires comparing columns in the parent and child tables. Requiring indexes in both tables allows this to be done just using indexes, rather than reading entire rows, which is more efficient.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25686&siteId=1