问题
In my table I have two closely related columns A and B. What possible considerations shall I made to decide whether to create:
- index(A) and index(B),
- index(A, B),
- both of the above?
How does this change if I:
- use only queries like
where A = 5 and B = 10(and never likewhere A = 5), - also use queries like
where A > 3 and A < 10 and B > 12 and B < 20, - often use
order by (A, B), - often use
group by (A, B)?
Note: I intentionally haven't provided more details about my particular case as I want a general answer that will also serve to others. I use mysql, but if you give more general answer that covers SQL in general that would be great.
回答1:
Ok, when you have an index(A,B), MySQL can also use it as an index(A). Declaring AB and A has no sense. Declaring AB and B does, however
So you have these choices:
- Index(A,B)
- Index(A,B) and Index(B)
- Index(A) and Index(B)
回答2:
If you always use both columns (or the first one of the index) in your WHERE / GROUP BY / ORDER BY you should use index(A,B).
The second one in the index (in this case B) cannot be used separately, but the first one can (only the first one in any case).
So if you never use B on its own, then index(A,B) should be sufficient. If you never use A on its own, but you do use B, then do index(B,A). If you do use both separately, but mostly together, then add the other index separately.
回答3:
An index on (A,B) will handle your cases 1, 3 and 4.
For case 2, where you have a range query on A and also on B, it's best to have an index on (A), and a separate index on (B), and let the database decide which is best for the query. It can decide on the fly which index is more selective based on the values in the query. MySQL will only use one index in this case, so it will pick which one it thinks will give it the smallest set of rows for the given range, and then will walk through those rows filtering by the other range.
So to handle all of those cases you mentioned, I recommend indices on:
(A,B)(B)
The index on (A,B) can be used just like an index just on (A) whenever the database needs an index on just (A), so defining those two indices is just like having an "all of the above" set of (A), (B) and (A,B).
Also note that if you ever want to order by or group by (B, A), you would want an index on (B,A) as well as (A,B). Order is important!
来源:https://stackoverflow.com/questions/9805768/shall-i-define-index-a-and-index-b-or-index-a-b-or-both