MySQL高级 :索引单表优化案例(单表)

注:
索引的建立:索引理解

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!

在这里插入图片描述
大功告成!

后面有关 两表案例
三表的案例!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值