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

谐音太郎 2011-08-27 05:44:34
我们用到了两个数据量比较大的表,表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秒之内。

不明何故,还望高手解释下。
...全文
510 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
谐音太郎 2011-08-27
  • 打赏
  • 举报
回复
感谢楼上~结贴~
ACMAIN_CHM 2011-08-27
  • 打赏
  • 举报
回复
原理讲起来得几千字。

你还是先看看以前的贴子吧。

http://topic.csdn.net/u/20090604/15/b4120d6f-fd95-4a60-be4b-fbd5accbea73.html?44678
http://topic.csdn.net/u/20090526/17/639d78ec-e299-40d0-9c8e-8d5b21229405.html?2724
http://topic.csdn.net/u/20090520/16/a96a2e90-a935-4460-837e-e52b4557c519.html?48098


如果想了解原理的话,则建议看一下《数据库系统概论》中的优化那一章节。
谐音太郎 2011-08-27
  • 打赏
  • 举报
回复
楼上说的是个好办法,但是我还是不明白这么慢的原理啊。
ACMAIN_CHM 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
谐音太郎 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
谐音太郎 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
谐音太郎 2011-08-27
  • 打赏
  • 举报
回复
不是 name like的问题,就算吧 name like 去掉也一样慢
nicenight 2011-08-27
  • 打赏
  • 举报
回复
当使用通配符的时候,放在首位的话是不能用到索引的,你可以把你的 sql 语句 explain 一下看看。如果不是 like "%a%" 的原因的话,那再看别的地方。
nicenight 2011-08-27
  • 打赏
  • 举报
回复
我看花眼了吗?我觉得是你那个 t1.name like "%a% 的原因吧……

56,681

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧