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

  • 相关阅读:
    一文读懂云渲染“串流”全链路时延及优化策略
    Linux开发工具之项目自动化构建工具-make/Makefile
    域控制器的深度详解!
    SpringBoot集成RabbitMQ使用建议
    【C++】笔试训练(四)
    javaEE幼儿园学生管理系统
    蓝桥杯_定时器的基本原理与应用
    洛谷 P7302 [NOI1998] 免费的馅饼
    ubuntu下查看realsense摄像头查看支持的分辨率和频率
    Visual Studio C++ 的 头文件和源文件
  • 原文地址:https://blog.csdn.net/xzj80927/article/details/134372937