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去重的代价非常高, 放在程序里去重.

原文地址:https://www.cnblogs.com/microtiger/p/7581045.html