MySQL index for MIN and MAX

前端 未结 2 2213
误落风尘
误落风尘 2021-02-15 12:38

Could anyone clarify this point from the official MySQL documentation

Indexes are used ... To find the MIN() or MAX() value for a specific indexed column

2条回答
  •  一生所求
    2021-02-15 12:58

    SELECT MIN(b), MAX(b) FROM tbl WHERE a = 12;
    

    loves

    INDEX(a, b)
    

    both columns, in that order.

    The query looks in the index for a = 12, grabs the first (a,b) pair to get MIN(b) and grabs the last pair to get MAX(b).

    The statement about "replacing with a constant" is confusing because it is going too deep into the details of how it first figures out how to perform the query (which happens to get the min and max), then proceeds to execute what is left of the query (nothing is left).

    More generally, the optimal index is usually one that starts with all the WHERE columns compared to constants with =. After that it gets complex, so let me give another tip:

    A "covering" index is one that has all the columns mentioned in the SELECT (a and b in my example).

    Sorry, I don't seem to be clearer than the manual.

提交回复
热议问题