我们用到了两个数据量比较大的表,表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秒之内。 不明何故,还望高手解释下。

解决方案 »

  1.   

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

  2.   

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

  3.   

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

  4.   

    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
      

  5.   

    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
      

  6.   

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

  7.   

    原理讲起来得几千字。你还是先看看以前的贴子吧。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
    如果想了解原理的话,则建议看一下《数据库系统概论》中的优化那一章节。