zoukankan      html  css  js  c++  java
  • MySQL 优化小技巧

    碎片整理:

    mysql数据一开始是在磁盘上顺序存放的,如果数据表有频繁的update改动,那么数据就会形成很多碎片,拖慢速度和不利于索引;

    优化碎片有两种方式:

    alter table user engine innodb;其实user这个表原先也是innodb的,这句话看上去没有任何意义,但是mysql会重新规整数据

    optimize table user; 也可以修复;

    碎片优化是一种很费cpu和内存的事,最好在夜里执行;

    非常规 的 min  max 优化

    select min(age) from table;

    不管table有多少数据,这条语句都是非常快的,因为mysql内部存到有相关的值,通过explain 可以看出已经被mysql优化过了;

    稍微改一下语句;

    select min(age) from table where status=1;

    通过explain 查看 是全表扫描;

    mysql要一行一行的取出来看status是不是1,如果是,那对比上一次的age看看那个小;有点想冒泡排序一样;

    有个特别的优化方式,要在age有索引的前提下;

    select min(age) from table use index(age) where status=1 limit 1;

    强制mysql使用age索引,因为索引是排好序的,所以取第一个就是最小值,max同理

    count非常规优化

    select count(*) from table;

    通过explain可以看出已经被mysql优化到常亮级别了;非常快

    但是:

    select count(*) from table where id>100;

    速度飞速下降,explain 已查看用到了全表扫描;从100开始扫描全表

    然而这条语句是很快的,只用扫描前100条:

    select count(*) from table where id<100;

    所以优化方法是利用数学加减法:

    ( select count(*) from table ) - ( select  count(*) from table where id<100 )

    union优化:

    连接查询结果的时候 如非必要 尽量使用 union all,因为union all 不过滤数据,效率高,而union要过滤数据,代价很大;

  • 相关阅读:
    zz[读书笔记]《Interpretable Machine Learning》
    Xgboost,LightGBM 和 CatBoost
    zz:Xgboost 导读和实战
    bzoj3252: 攻略 优先队列 并查集 贪心
    [BeiJing2009 WinterCamp]取石子游戏 Nim SG 函数
    Playing With Stones UVALive
    Division Game UVA
    [BJWC2011]禁忌 AC 自动机 概率与期望
    [Jsoi2010]连通数 bitset + Floyd
    洛谷P2197 nim游戏模板
  • 原文地址:https://www.cnblogs.com/codeAB/p/6391627.html
Copyright © 2011-2022 走看看