zoukankan      html  css  js  c++  java
  • SQL 优化

    1.为什么需要优化sql

      不好的sql可能存在的问题:性能低、执行时间长、等待时间长、sql语句欠佳(连接查询)、索引失效、服务器参数设置不合理(缓冲区、线程数)

      编写过程:select distinct..  from..  join..on.. where.. group by.. having.. order by..  limit..

      解析过程:from.. on.. join.. where.. group by.. having.. select distinct.. order by.. limit.. 

    2.索引

      第一步可以从索引入手,sql优化主要就是在优化索引

      索引相当于书的目录,可以是B+树结构、hash结构,会占用一定的空间

      安利一个蛮好用的网站

    https://www.cs.usfca.edu/~galles/visualization/Algorithms.html

      优点:索引可以提高查的效率,提高  order by column 排序的效率(因为树本身就排好序了)

      缺点:索引会降低增删改的效率,所以对于频繁更新的字段不适用(一个表查询操作比增删改要频繁的多)

      下面,以一个B树来直观展示一下索引的查询流程(注意,mysql使用的是b+树,这里只是为了展示)

      如果执行:

    select * from user where age=44

      在没有索引的情况下得从上到下查询,需要6次比较,添加了索引呢,只需要4次

      不过,我们得清除索引的应用场景,对于基本有序的列,使用索引并不明智,如上面的 id,B树为

      

      可以很直观的看出来,查找次数并没有减少。

      索引的创建

    /*create 创建索引 (单值索引、唯一索引、复合索引)*/
    create index index_name on table_name(column1);
    create unique index index_name on table_name(column1);
    create index index_name on table_name(column1,column2);
    /*alter 添加索引 (单值索引、唯一索引、复合索引)*/
    alter table table_name add index index_name(column1);
    alter table table_name add unique index index_name(column1);
    alter table table_name add index index_name(column1,column2);

       索引的查询和删除

    /*查询*/  show index from table_name;
    /*查询索引可以当成查询一个表来操作 比如可以加上where 例如:show index from tb_user where key_name='UserIndex'*/
    /*删除*/ drop index index_name on table_name;

     3.  mysql优化

      

      

      

  • 相关阅读:
    gitlab Failed to register this runner. Perhaps you are having network problems runner 注册失败问题解决
    gitlab pipelines 使用
    centos 7 bbr 安装
    kafka ksql && docker 安装试用
    netflix vector 系统性能监控安装使用
    keycloak && docker安装 &&spring boot 集成使用
    gogs docker 安装
    alpine docker 镜像 时区问题
    nginx 流量拷贝模块 ngx_http_mirror_module 安装试用
    ulimit  设置
  • 原文地址:https://www.cnblogs.com/wskxy/p/11111673.html
Copyright © 2011-2022 走看看