zoukankan      html  css  js  c++  java
  • min/max优化,count ,group by

    min/max优化 在表中,一般都是经过优化的. 如下地区表

    id

    area

    pid

    1

    中国

    0

    2

    北京

    1

    ...

    3115

    3113

    我们查min(id), id是主键,查Min(id)非常快.

    但是,pid上没有索引, 现在要求查询3113地区的min(id);

    select min(id) from it_area where pid=69; 

    试想 id是有顺序的,(默认索引是升续排列), 因此,如果我们沿着id的索引方向走,

    那么  第1个 pid=69的索引结点,他的id就正好是最小的id.

    select  id  from it_area use index(primary) where pid=69 limit 1;

    |       12 | 0.00128100 | select min(id) from it_area where pid=69                         |

    |       13 | 0.00017000 | select id from it_area  use index(primary) where pid=69  limit 1 |

    改进后的速度虽然快,但语义已经非常不清晰,不建议这么做,仅仅是实验目的.

    count() 优化

    误区:

    1:myisam的count()非常快

    答: 是比较快,.但仅限于查询表的”所有行”比较快, 因为Myisam对行数进行了存储.

    一旦有条件的查询, 速度就不再快了.尤其是where条件的列上没有索引.

    2: 假如,id<100的商家都是我们内部测试的,我们想查查真实的商家有多少?

    select count(*) from lx_com where id>=100;  (1000多万行用了6.X秒)

    小技巧:

    select count(*) from lx_com; 快

    select count(*) from lx_com where id<100; 快

    select count(*) frol lx_com -select count(*) from lx_com where id<100; 快

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

    3: group by 是可以用索引的

    注意:

    1:分组用于统计,而不用于筛选数据.

    比如: 统计平均分,最高分,适合, 但用于筛选重复数据,则不适合.

    以及用索引来避免临时表和文件排序

    2:  以A,B表连接为例 ,主要查询A表的列,

    那么 group by ,order by 的列尽量相同,而且列应该显示声明为A的列

    4: union优化

    注意: union all 不过滤 效率提高,如非必须,请用union all

    因为 union去重的代价非常高, 放在程序里去重.

  • 相关阅读:
    ios中的几种多线程实现
    在mac下使用终端管理svn
    关于UIScrollViewDelegate协议中每个回调函数的意义及执行顺序的理解
    UIView 及其子类对象 抖动效果的实现
    ios、andriod、cocos2d 视图层次理解
    委托  通知中心   监听/观察
    iphone 中使用苹果禁用的私有Framework
    关于苹果官方网站Reachability检测网络的总结
    iOS设备的分辨率
    ios开发多线程、网络请求的理解 错误码的理解
  • 原文地址:https://www.cnblogs.com/microtiger/p/7581045.html
Copyright © 2011-2022 走看看