MySQL indices and order

前端 未结 3 998
长发绾君心
长发绾君心 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 12:00

    Why not to extend the answer a little bit to make completely everything crystal clear at once.

    If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3).

    MySQL cannot use an index if the columns do not form a leftmost prefix of the index. Suppose that you have the SELECT statements shown here:

    SELECT * FROM tbl_name WHERE col1=val1;
    SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
    
    SELECT * FROM tbl_name WHERE col2=val2;
    SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;
    

    If an index exists on (col1, col2, col3), only the first two queries use the index. The third and fourth queries do involve indexed columns, but (col2) and (col2, col3) are not leftmost prefixes of (col1, col2, col3). - MySQL dev

提交回复
热议问题