调优一个sql语句,在语句如下
select resources_id,title,file_type,period,subject_id,subject_name  from cms_resources
         where status=2
         and  period="2"
         and subject_id=6
         and FIND_IN_SET("114",category_id)>0
         and FIND_IN_SET("264",category_id)>0
         and FIND_IN_SET("705",category_id)>0
           and FIND_IN_SET(7,type)>0 
 order by update_time desc limit 0,1
之前看是没有这个索引,增加索引后,查询时间依然大于7秒。
然后一点点测试,发现到如下情况时,依然返回只需 700多毫秒。
select resources_id,title,file_type,period,subject_id,subject_name  from cms_resources
         where status=2
         and  period="2"
         and subject_id=6
         and FIND_IN_SET("114",category_id)>0
         and FIND_IN_SET("264",category_id)>0
         and FIND_IN_SET("705",category_id)>0
           and FIND_IN_SET(7,type)>0 
 order by update_time desc
然后只有在加上: limit 0,1 后,查询时间才会变为大于 7秒。
原因:
后来查证mysql官方文档,在order 的同时使用limit,将会对所有数据进行扫描重排,所以效率差。
改进为:
select * from (
 select resources_id,title,file_type,period,subject_id,subject_name,category_id  from cms_resources
         where status=2
         and  period="2"
         and subject_id=6
         and FIND_IN_SET("114",category_id)>0
         and FIND_IN_SET("264",category_id)>0
         and FIND_IN_SET("704",category_id)>0
           and FIND_IN_SET(7,type)>0  
 order by update_time desc   ) t2
 limit 0,1
查询时长恢复700多毫秒。效率很高,而且无序再程序上进行改动了。