+ -
当前位置:首页 → 问答吧 → 请教关于MYSQL中order by的效率优化

请教关于MYSQL中order by的效率优化

时间:2011-08-27

来源:互联网

我们用到了两个数据量比较大的表,表table1和表table2,每个表的数据都是四五百万条。 
table1三个字段:id(主键),age,name 
table2两个字段:id(主键),status 

执行下面的查询语句: 
select t1.* from table1 as t1 inner join table2 as t2 on t1.id=t2.id where t1.age>=18 and t1.name like '%a%' order by t2.status desc,t1.id desc limit 10 

查询耗时:25秒左右。 
一开始只有name有索引,在排查问题过程中我们给table2的status加上了索引。但是查询耗时并没有减少。 


后来发现是对两个表的两个字段进行order by导致的。 
单独执行order by t2.status desc或者order by t1.id desc查询时间都在0.1秒之内。 

不明何故,还望高手解释下。

作者: shootyou   发布时间: 2011-08-27

我看花眼了吗?我觉得是你那个 t1.name like "%a% 的原因吧……

作者: nicenight   发布时间: 2011-08-27

当使用通配符的时候,放在首位的话是不能用到索引的,你可以把你的 sql 语句 explain 一下看看。如果不是 like "%a%" 的原因的话,那再看别的地方。

作者: nicenight   发布时间: 2011-08-27

不是 name like的问题,就算吧 name like 去掉也一样慢

作者: shootyou   发布时间: 2011-08-27

select t1.* from table1 as t1 inner join table2 as t2 on t1.id=t2.id where t1.age>=18 order by t2.status desc,t1.id desc limit 10 

查询时间:23.013s

作者: shootyou   发布时间: 2011-08-27

select t1.* from table1 as t1 inner join table2 as t2 on t1.id=t2.id where t1.age>=18 order by t2.status desc limit 10  

查询时间:0.047s

作者: shootyou   发布时间: 2011-08-27

创建索引table2 (id,status) 另外不要用 order by t2.status desc,t1.id desc limit 10 应该用 order by t2.status desc,t2.id desc limit 10

作者: ACMAIN_CHM   发布时间: 2011-08-27