MySql优化-04

来源:互联网 发布:印度与中国 知乎 编辑:程序博客网 时间:2024/05/14 20:52

1:limit 分页及优化

   select * from table limit 10000,5  查询原理是 先查到10005 条记录,然后不要前10000条 取最后5的条,这样会使得查询效率非常的慢

   limit offset,5 随着offset的增大limit 的效率越来越低 查询所花费的时间越来越长

   set profiling=1

   show profiles;

   show profile for query 5;  //查看 5条记录

2:对于需求 查询第10000 页之后的 5条数据优化方法

   方式一: id 按照一次递增的顺序排好,没有中间删除的情况存在

                  假设 id 1 2 3 4 5 6 7 ....

                  select *from table where id >5 limit 3 就查询到的 offset 后的3条记录了 ,这样可以用到索引去查询。

                  但是前提是必须要id是不能被删除的。可以在遇到删除Id的时候进行逻辑上的删除,不去真的删除。这样保证最后查询结果的正确性。

  方式二:如果数据必须删除的话,一下方式可以用到索引覆盖

                select * from lx_com inner join (select id from lx_com limit 100000,3) as tmp on lx_com.id = tmp.id

                 内部可以用到 id 主键索引 ,然后再去查询,这样可以延迟关联时间。提高翻页速度

3:强制使用索引

     需要排序尽量做到在内部子句进行排序,不在外层排序

     select  max(id) froom area where pid=10;

     select id from area use index(primary) where pid=10 order by id desc limit 1   同样找到的是最大值,并且使用索引

4:group by 和 order by  应该后面的字段应该一致

5 : union 和 union all 

     union 会去掉重复内容

     union all 不会去掉重复内容

6:count(*) 子句对于Myisam 来说 是很方便的  因为 引擎本身就就记录一个 记录总数

     但是如果不查询全部信息的话

     select  count(*) from lx_com where id > 5;// 这样就需要去一条一条的统计记录了

     优化的方式

     用总数-<=5的记录数

     select ((select count(*) from lx_com)-(select count(*) from lx_com where id <=5));