zoukankan      html  css  js  c++  java
  • msyql 优化之五不要

    1、尽量不要有空判断的语句,因为空判断将导致全表扫描,而不是索引扫描。

         对于空判断这种情况,可以考虑对这个列创建数据库默认值

    //空判断将导致全表扫描
    select small_id  from  small  where  sunshine  is  null;
    //可以考虑在需要经常null判断的列,增加默认值。假设有默认值:空字符串
    select small_id  from  small  where  sunshine ="";
    

    2、尽量不要使用不等于条件,因为,这会导致全表扫描

         对于不等于这种情况,考虑改为范围查询解决

    //不等于条件  将导致全表扫描
    select  sunshine  from   small  where  small_id  <> 18;
    //可改为范围查询解决。假设18已经是最大值了
    select  sunshine  from   small  where  small_id  < 18
    

    3、尽量不要使用or条件,因为,这会导致全表扫描

         对于or这种情况,可以改为 分别查询,然后 union all

    //or条件,将导致全部扫描
    select sunshine from  small  where  small_id = 6  or small_id = 8;
    //改为分别查询,然后 union all 
    select sunshine from  small  where  small_id = 6
    union all
    select sunshine from  small  where  small_id = 8;
    

    4、尽量不要使用左右模糊查询,因为,这会导致全表扫描

         对于左右模糊查询的情况,试着改为右侧模糊查询,这样是可以索引查找的

    //左右模糊查询,将导致全表扫描
    select  small_id  from  small  where  sunshine  like '%fun%';
    //改为右侧模糊查询
    select  small_id  from  small  where  sunshine  like 'fun%';
    

    5、尽量不要使用in条件,因为,这会导致全表扫描,宜用exists代替

    //in查询,将导致全表扫描
    select  sunshine  from  small where small_id  in  (select  sun_id  from  sun  where index = "shine");
    //改为exists
    select  sunshine  from  small  where  small_id  exists  (select sun_id from sun where  index ="shine")
    缘于生活,而归于工作。本人所书,而意于分享。 如有转载,请注明出处! --活出自己范儿
  • 相关阅读:
    Java开源框架推荐(全)
    Java性能提示(全)
    国外程序员整理的 C++ 资源大全 (zt)
    技术杂记之:在阿里云centos7上部署JDK MYSQL TOMCAT
    技术杂记之:vi使用入门
    Java全栈程序员之09:IDEA+GitHub
    SpringCloud无废话入门05:Spring Cloud Gateway路由、filter、熔断
    SpringCloud无废话入门04:Hystrix熔断器及监控
    SpringCloud无废话入门03:Feign声明式服务调用
    SpringCloud无废话入门02:Ribbon负载均衡
  • 原文地址:https://www.cnblogs.com/Small-sunshine/p/10893294.html
Copyright © 2011-2022 走看看