注:
索引的建立:索引理解
1.建表:
create table if not exists article(
id int(10) unsigned not null primary key auto_increment,
author_id int(10) unsigned not null,
category_id int(10) unsigned not null,
views int(10) unsigned not null,
comments int(10) unsigned not null,
title varchar(255) not null,
content text not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into article(author_id ,category_id ,views,comments , title, content)
values(1,1,1,1,'1','1'),
(2,2,2,2,'2','2'),
(1,1,3,3,'3','3');
select * from article;
2.案例:
2.1:
explain select id,author_id from article
where categoy_id =1 and comments >1
order by views desc limit 1;
结果:
过程分析:
首先是 all 全表查询出现最差的情况,而且出现 using filesort 情况也很糟糕,需要优化!!
2.11 优化 : 建立索引 idx_arcticle_ccv
建立索引不会的去看: 关于索引理解
格局where后面的字段先尝试建立索引:
create index idx_arcticle_ccv on article( category_id,comments,views);
建立成功:
再次分析建立索引后的过程:
显然索引有被用到,ALL---->range , 但是 using filesort 依然存在。
由于 comments >1 是范围使得 索引失效
但是 当 comments =1时:看下图,效果已经很好了!!!
但但是 题目 不是等于1!!
索引的建立不是一朝一夕就,一次建成。
继续优化!!
删掉上一个索引重新来:
drop index idx_arcticle_ccv on article;
2.12 再次建立新索引: idx_arcticle_cv
create index idx_arcticle_cv on article( category_id,views);
来看结果:
这次就有了我们想要的结果! ALL–> ref , 并且还没有了using filesort!
大功告成!