Indexing rules - try to use covering indexes

 

Mysql series article home page 

 

===============

 

1 Prepare data

1.1 Create a table

DROP TABLE IF EXISTS staff;
CREATE TABLE IF NOT EXISTS staff (
    id INT PRIMARY KEY auto_increment,
    name VARCHAR(50),
    age INT,
    pos VARCHAR ( 50 ) COMMENT ' Position ' ,
    salary DECIMAL(10,2)
);

1.2 Insert data

INSERT INTO staff(name, age, pos, salary) VALUES('Alice', 22, 'HR', 5000);

2 Test & Explain Analysis

2.1 Create an index

CREATE INDEX idx_nameAgePos ON staff(name, age, pos);

2.2 Testing

Case#1:

EXPLAIN SELECT * FROM staff where name = 'Alice' AND age = 22 AND pos = 'HR';

Note: 'SELECT *' is used in SELECT, and 'Using index condition' is used in Extra

Case#2:

EXPLAIN SELECT name, age, pos FROM staff where name = 'Alice' AND age = 22 AND pos = 'HR';

Note: SELECT is 'SELECT name, age, pos', and Extra is 'Using where; Using indx'

 

Which is better 'Using where; Using indx' or 'Using index condition'? I haven't fully understood it yet, and I can't give a complete answer. The clues that can be provided are as follows.

An answer found on StackOverFlow, you can refer to the address: https://stackoverflow.com/questions/28759576/mysql-using-index-condition-vs-using-where-using-index

 

Meanwhile, the screenshot is as follows:

A simple translation is as follows:

  • 'Using index condition': Where condition contains indexed and non-indexed columns, the query optimizer will first parse the indexed columns and query the rows of other conditions from the table
  • 'Using where; Using indx': 'Using index' means that the entire table does not need to be scanned. 'Using where' may still do a full table scan on non-indexed columns, but it will use the index first, if there are any indexed columns in the Where condition, just like using the index condition
  • Which one is better? 'Using where; Using indx' would be better than 'Using index condition' if it was all covering indexes.

I feel that I am still confused, and the translation is too blunt,,,,,,,,,,,, and then I will add and improve it after I understand it thoroughly. . . . . TODO

But as you can see from the above example, 'SELECT name, age, pos' corresponds to 'Using where; Using indx', which is full index coverage; and 'SELECT *' corresponds to 'Using index condition', which The four fields of name, age, pos, and salary will be queried, and salary is not on the index. So, for sure, 'Using where; Using indx' would be better than 'Using index condition'.

3 Conclusion

Use covering indexes as much as possible - queries that only access the index (index columns and query columns are consistent), reduce SELECT *

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820135&siteId=291194637