开发者

Is there a performance benefit to creating a multiple index on a primary key + foreign key?

开发者 https://www.devze.com 2023-04-07 07:51 出处:网络
If I have a table that has a primary key and a foreign key, and searches are frequently done with queries that include both (...WHERE primary=n AND foreign=x), is开发者_如何学Python there any performa

If I have a table that has a primary key and a foreign key, and searches are frequently done with queries that include both (...WHERE primary=n AND foreign=x), is开发者_如何学Python there any performance benefit to making a multiple index in MySQL using the two keys?

I understand that they are both indexes already, but I am uncertain if the foreign key is still seen as an index when included in another table. For example, would MySQL go to the primary key, and then compare all values of the foreign key until the right one is found, or does it already know where it is because the foreign key is also an index?

Update: I am using InnoDB tables.


For equality comparisons, you cannot get an improvement over the primary key index (because at that point, there is at most just one row that can match).

The access path would be:

  1. look at the primary key index for primary = n
  2. get the single matching row from the table
  3. check any other conditions using the row in the table

A composite index might make some sense if you have a range scan on the primary key and want to narrow that down by the other column.

0

精彩评论

暂无评论...
验证码 换一张
取 消