我用的数据库是mysql5.6,下面简单的介绍下场景
课程表
create table Course( c_id int PRIMARY KEY, name varchar(10) )
数据100条
学生表:
create table Student( id int PRIMARY KEY, name varchar(10) )
数据70000条
学生成绩表SC
CREATE table SC( sc_id int PRIMARY KEY, s_id int, c_id int, score int )
数据70w条
查询目的:
查找语文考100分的考生
查询语句:
select s.* from Student s
where s.s_id in (
select s_id from SC sc
where sc.c_id = 0and sc.score = 100
)
执行时间:30248.271s
晕,为什么这么慢,先来查看下查询计划:
EXPLAIN
select s.* from Student s
where s.s_id in (
select s_id from SC sc
where sc.c_id = 0and sc.score = 100
)
发现没有用到索引,type全是ALL,那么首先想到的就是建立一个索引,建立索引的字段当然是在where条件的字段。
先给sc表的c_id和score建个索引
CREATE index sc_c_id_index on SC(c_id); CREATE index sc_score_index on SC(score);
再次执行上述查询语句,时间为: 1.054s
快了3w多倍,大大缩短了查询时间,看来索引能极大程度的提高查询效率,建索引很有必要,很多时候都忘记建
索引了,数据量小的的时候压根没感觉,这优化的感觉挺爽。
但是1s的时间还是太长了,还能进行优化吗,仔细看执行计划:
查看优化后的sql:
SELECT `YSB`.`s`.`s_id` AS `s_id`, `YSB`.`s`.`name` AS `name` FROM `YSB`.`Student` `s` WHERE < in_optimizer > ( `YSB`.`s`.`s_id` ,< EXISTS > ( SELECT 1 FROM `YSB`.`SC` `sc` WHERE ( (`YSB`.`sc`.`c_id` = 0) AND (`YSB`.`sc`.`score` = 100) AND ( < CACHE > (`YSB`.`s`.`s_id`) = `YSB`.`sc`.`s_id` ) ) ) )
补充:这里有网友问怎么查看优化后的语句
方法如下:
在命令窗口执行
mysql>explain extended select s.* from Student s where s.s_id in ( select s_id from SC sc where sc.score=100 and sc.c_id=0 )
有type=all
按照我之前的想法,该sql的执行的顺序应该是先执行子查询
select s_id from SC sc where sc.c_id = 0 and sc.score = 100
耗时:0.001s
得到如下结果: