点击查看MySQL优化系列文章集锦,从头到尾全部案例均配备源码,让你轻松看文章,轻松实践
如你不想自己测试案例,可直接看优化总结,了解知识点即可
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` VARBINARY(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');
查询category_ id 为1且comments大于1的情况下,views最多的文章ID
select id,author_id from article where category_id=1 and comments>1 order by views;
可以看到进行了全表扫描,并且使用了文件排序 这种SQL是必须进行优化的
# 创建索引
create index ind_article_ccv on article(category_id,comments,views);
# 查看表的所有索引
show index from article
explain select id,author_id from article where category_id=1 and comments>1 order by views;
发现全表扫描我们解决了,但是文件排序还没有解决。那么这个方案也是不可以的
# 删除索引
drop index ind_article_ccv on article
# 查看表的所有索引
show index from article
那么我们在来给caterory_id和view建立一个索引
# 创建索引
create index ind_article_cv on article(category_id,views);
# 分析语句
explain select id,author_id from article where category_id=1 and comments>1 order by views;