索引法则--尽量使用覆盖索引

 

Mysql 系列文章主页 

 

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

 

1 准备数据

1.1 建表

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 '职位',
    salary DECIMAL(10,2)
);

1.2 插入数据

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

2 测试&Explain分析

2.1 创建索引

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

2.2 测试

Case#1:

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

注意:SELECT中使用了 'SELECT *' ,且Extra中是 'Using index condition'

Case#2:

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

注意:SELECT中是 'SELECT name, age, pos',且Extra中是 'Using where; Using indx'

 

那 'Using where; Using indx' 和 'Using index condition' 哪个更好呢?自己也还没有完全理解,给不了完整的回答,能提供的线索有下面一些。

从 StackOverFlow 上找到的一个回答,可以参考,地址:https://stackoverflow.com/questions/28759576/mysql-using-index-condition-vs-using-where-using-index

 

同时,截图如下:

简单翻译如下:

  • 'Using index condition':Where条件包含索引和非索引的列,查询优化器将首先解析索引列同时从表中查询其它条件的行
  • 'Using where; Using indx':'Using index' 意味着不需要扫描整个表。'Using where' 在非索引的列上可能仍然会做全表扫描,但是它会首先使用索引,如果在Where条件中有任何索引列的话,就像使用索引条件那样
  • 哪个一个更好?'Using where; Using indx' 会比 'Using index condition' 更好,如果全部是覆盖索引的话。

感觉自己也还是蒙蒙的,,翻译也是,太生硬了,,,,,,,,,,,待以后理解透彻后再来补充和完善吧。。。。。TODO

不过从上面的例子中可以看到,'SELECT name, age, pos' 对应的是 'Using where; Using indx',这是全索引覆盖;而 'SELECT *' 对应的是 'Using index condition',这会查询 name, age, pos, salary 四个字段,而 salary 是不在索引上的。所以,可以肯定的是,'Using where; Using indx' 会比 'Using index condition' 更好。

3 结论

尽量使用覆盖索引——只访问索引的查询(索引列和查询列一致),减少 SELECT *

 

posted @ 2018-04-24 14:35  cyhbyw  阅读(642)  评论(1编辑  收藏  举报