MySQL高级(三) 索引Case

164 阅读1分钟
  • 不是很理解, 跟着视频看得 仅仅记录一下

explain 语句顺序案例

  1. id = 4 t2表全表扫描, 没有用到索引, 行数为1 select name,id from t2
  2. id = 3 t1表用到where的全表扫描 select id ,name from t1 where ....
  3. id = 2 t3表用到了主键, 覆盖索引, 行数为1 select id from t3
  4. id = 1 来源于id=3 , 系统级 只有一行 select d1.name
  5. union id = 1, id =4 的结果union

索引分析

数据表

案例1

explain select id, author_id from article where category_id = 1 AND  comments > 1 order by  views DESC limit 1;

type = all, filesort都是不好的情况

查看索引

show index from article;

只有一个主键

创建索引

create index idx_article_ccv on article(category_id, comments, views)

结果

  • 索引不太合适
  • 删掉索引
drop index idx_article_ccv on article;
  • create index article_cv on article(category_id, views);
create index article_cv on article(category_id, views);

重新测试结果