• mysql 添加limit,sql 语句执行时间变长的问题


    调优一个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多毫秒。效率很高,而且无序再程序上进行改动了。

  • 相关阅读:
    画一条0.5px的线、设置小于12px的字体、解决 1px 问题
    WebRTC学习笔记二 基础概念
    el-select multiple表单校验问题
    大数据集群修改服务器ip
    nginx-proxy反向代理流程
    SpringBoot集成Lombok
    Dubbo高手之路2,6种扩展机制详解
    颠覆IoT行业的开发神器!涂鸦智能重磅推出TuyaOS操作系统【程序员必备】
    《style scope》 作用域保护如何修改(组件库)子组件的样式
    MySQL-锁机制
  • 原文地址:https://blog.csdn.net/xzj80927/article/details/134372937