MySQL indices and order

前端 未结 3 991
长发绾君心
长发绾君心 2020-12-02 11:44

This is a question that I\'ve had forever.

As far as I know the order of indices matter. So an index like [first_name, last_name] is not the same as

3条回答
  •  眼角桃花
    2020-12-02 11:54

    Index order matters when your query conditions only apply to PART of the index. Consider:

    1. SELECT * FROM table WHERE first_name="john" AND last_name="doe"

    2. SELECT * FROM table WHERE first_name="john"

    3. SELECT * FROM table WHERE last_name="doe"

    If your index is (first_name, last_name) queries 1 and 2 will use it, query #3 won't. If your index is (last_name, first_name) queries 1 and 3 will use it, query #2 won't. Changing the condition order within WHERE clause has no effect in either case.

    Details are here

    Update:
    In case the above is not clear - MySQL can only use an index if the columns in query conditions form a leftmost prefix of the index. Query #2 above can not use (last_name, first_name) index because it's only based on first_name and first_name is NOT the leftmost prefix of the (last_name, first_name) index.

    The order of conditions WITHIN the query does not matter; query #1 above will be able to use (last_name, first_name) index just fine because its conditions are first_name and last_name and, taken together, they DO form a leftmost prefix of (last_name, first_name) index.

提交回复
热议问题