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
);
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');
  1. 问题提出:查询category_id为1且comments大于1的情况下,views最多的article_id
  2. 问题分析:可以将category_id和comments作为where的查询条件,根据views排序,限制显示一条信息即可
  3. SQL语句:
select id,author_id from article where category_id = 1 and comments > 1 order by views desc limit 1;

查询是可以的:
执行查询结果 5. 使用 explain 关键字进行分析:
在这里插入图片描述出现了type=ALL和Extra 含有 using filesort 情况,这是我们极其不愿意看到的全表查询和使用文件排序,产生临时表,key为NULL表示实际上也没有用到索引
5. 在创建表的时候是没有创建索引的,接下来我们为表创建多值索引(因为我们需求用到了其中三个索引)

create index ccv on article(category_id,comments,views);
  1. 再来执行上面 explain分析语句:
    在这里插入图片描述
  2. 显然type从All变为了 range,这是我们希望看到的,但是,从extra列看,还存在使用文件排序的情况,我们知道,使用filesort原因是索引值存在范围情况,不唯一,如果我们把 comments > 1 改成 comments = 1,我们再来看:
    在这里插入图片描述type直接从 range 级别到了 ref 级别,也不存在 filesort 了,所以给我们一个提示,存在 filesort 是因为comments这一查询条件不唯一,接下来我们把索引改一下,去掉comments这一列试试:
drop index ccv on article;
create index cv on article(category_id,views);
  1. 在来看 explain 执行情况:
    在这里插入图片描述这样,再次查询需求完成了,性能方面也符合了需要,这仅仅是一个索引优化的小案例,希望对大家有帮助!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值