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")
    缘于生活,而归于工作。本人所书,而意于分享。 如有转载,请注明出处! --活出自己范儿
  • 相关阅读:
    数据结构01-线性表
    java-04流程控制语句
    从0开始的Python学习002python的数据类型
    从0开始的Python学习001快速上手手册
    MySQl ifnull()和substr()
    parent.fraInterface.xxxxxx
    身份证的校验规则
    onclick="return function()"的使用情况
    jsp include 报错:illegal to have multiple occurrences of contentType with different values (old: text/html; charset=UTF-8, new: text/html; carset=UTF-8)
    Oracle数据库忘记用户名密码的解决方案
  • 原文地址:https://www.cnblogs.com/Small-sunshine/p/10893294.html
Copyright © 2011-2022 走看看