简体   繁体   中英

MySQL will a composite index suffice a query that uses a JOIN?

As I understand, composite indexes will accomplish what is needed in cases like this:

SELECT name FROM user WHERE id_city = 3 AND id_type = 5

The INDEX would be (id_city, id_type). As long as all queries always filter those 2 combined fields, no other index would be ever necessary.

But what about queries where one of the fields is being used in the JOIN statement and the other one in the WHERE statement? Example:

SELECT user.name AS name
FROM user JOIN friend ON friends.id_str = user.id_str
WHERE friends.id_user = 3

Would the (id_user, id_str) INDEX be enough in the friends table? (btw, i'm not asking about the user table, that's of course another case).

EXPLAIN of current SELECT: 在此处输入图片说明

For your initial query, yes, (id_city, id_type) in either order is optimal. Tacking on name last would be slightly better (due to being "covering").

Moving on...

For that specific query, have these indexes:

friend:   (id_user, id_str)  -- in this order; "covering"
user:     (id_str, name)     -- in this order; "covering"

Here is what is going on:

  1. The Optimizer sees JOIN and some stuff about one of the tables ( friends ) in the WHERE , so it decides to start with friend .
  2. To handle the WHERE , it needs an index starting with what is in WHERE , namely id_str .
  3. Since there is not much else needed from friend , let's put all the columns in the index, hence "covering". EXPLAIN will indicate such by saying Using index .
  4. Now, to get to the other table ( user ). The ON clause needs id_str , so put it first in an index.
  5. Again, let's play the covering game by adding on name .

I cover this stuff more generically here .

If your real query looks different in any way , then all bets are off. That is, the indexes I suggest may or may not be beneficial.

If you want to discuss further, please provide

  • SHOW CREATE TABLE
  • The real queries.

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