索引分析:
explain :select id,author_id from article where category_id =1 and comments >1 order by views desc limit 1;
type 为 ALL , Using filesort (自己进行了排序没有用到索引);
查看 article 表有什么索引: show index from article;
只有一个主键
创建索引:
where 后面的字段需要建索引,但不一定必须建。
尝试着去建:
alter table “表名 ” ADD INDEX 索引名 ('字段名','字段名');
或者:
create index 索引名 on 表名 (‘字段名’,‘字段名’);
然后查看字段:
show index from 表名;
然后看看加完索引的结果:
比较加完索引与不加索引的区别;
type :由 ALL 变为了 range ,很好的改变
但是 Extra 还有:Using filesort;
如果将 comments> 1 变为 comments =1
结果会很不一样
当where 后面的索引字段 出现范围时 如 上面的comments > 1 ,索引是无法使用的,以及后面的索引字段 view。
进一步优化:
更换索引:
drop index 索引名 ON 表明;
跳过 comments ,直接跳过comments 这个字段 ,用categroy 和 view 创建索引:
create index idx_article_cv on article(categroy_id,view);
explain select id ,author_id from article where categroy_id=1 AND comments >1 order by views desc Limit 1;