MySQL EXPLAIN: “Using index” vs. “Using index condition”

前端 未结 2 1723
有刺的猬
有刺的猬 2020-12-12 22:51

The MySQL 5.4 documentation, on Optimizing Queries with EXPLAIN, says this about these Extra remarks:

  • Using index

The co

相关标签:
2条回答
  • 2020-12-12 23:16

    An example explains it best:

    SELECT Year, Make --- possibly more fields and/or from extra tables
    FROM myUsedCarInventory
    WHERE Make = 'Toyota' AND Year > '2006'
    
    Assuming the Available indexes are:
      CarId
      VIN
      Make
      Make and Year
    

    This query would EXPLAIN with 'Using Index' because it doesn't need, at all, to "hit" the myUsedCarInventory table itself since the "Make and Year" index "cover" its need with regards to the elements of the WHERE clause that pertain to that table.

    Now, imagine, we keep the query the same, but for the addition of a condition on the color

    ...
    WHERE Make = 'Toyota' AND Year > '2006' AND Color = 'Red'
    

    This query would likely EXPLAIN with 'Using Index Condition' (the 'likely', here is for the case that Toyota + year would not be estimated to be selective enough, and the optimizer may decide to just scan the table). This would mean that MySQL would FIRST use the index to resolve the Make + Year, and it would have to lookup the corresponding row in the table as well, only for the rows that satisfy the Make + Year conditions. That's what is sometimes referred as "push down optimization".

    0 讨论(0)
  • 2020-12-12 23:18

    The difference is that "Using index" doesn't need a lookup from the index to the table, while "Using index condition" sometimes has to. I'll try to illustrate this with an example. Say you have this table:

    id, name, location
    

    With an index on

    name, id
    

    Then this query doesn't need the table for anything, it can retrieve all it's information "Using index":

    select id, name from table where name = 'Piskvor'
    

    But this query needs a table lookup for all rows where name equals 'Piskvor', because it can't retrieve location from the index:

    select id from table where name = 'Piskvor' and location = 'North Pole'
    

    The query can still use the index to limit the results to the small sets of row with a particular name, but it has to look at those rows in the table to check if the location matches too.

    0 讨论(0)
提交回复
热议问题