mysql----其他小技巧

小技巧:

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=3113//全表扫描,找出所有pid=3113的,然后求出最小的id

 

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

那么  1pid=3113的索引结点,他的id就正好是最小的id,强制使用主键索引。

select  id  from it_area use index(primary) where pid=3113 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:myisamcount()非常快

: 是比较快,.但仅限于查询表的”所有行”比较快, 因为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 emp) - (select count(*) from emp where empno<100)

 

3: group by

注意:

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

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

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

 

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

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

 

4: union优化

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

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

posted @ 2018-01-16 17:11  无天666  阅读(206)  评论(0编辑  收藏  举报