当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql高效分页详解

Mysql高效分页详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

前言

通常针对mysql大数据量的查询采取“分页”策略,但是如果翻页到比较靠后的位置时查询将变得很慢,因为mysql将花费大量的时间来扫描需要丢弃的数据。

基本分页技巧

通常情况下,为了实现高效分页,需要在查询中where条件列和排序列应用组合索引。
例如,建立索引(a,b,c)使得以下查询可以使用索引,提高查询效率:

1、字段排序

order by a 
order by a,b
order by a, b, c 
order by a desc, b desc, c desc 

2、筛选和排序

where a = const order by b, c 
where a = const and b = const order by c 
where a = const order by b, c 
where a = const and b > const order by b, c 

3、下面查询是无法使用以上索引的

order by a asc, b desc, c desc//排序方向不一致
where g = const order by b, c // 字段g不是索引一部分
where a = const order by c //没有使用字段b 
where a = const order by a, d // 字段d不是索引的一部分 

解决大数据量翻页问题

1、将limit m,n的查询改为limit n
例如,使用limit 10000,20,mysql将需要读取前10000行,然后获取后面的20行 ,这是非常低效的,使用limit n的方式,通过每页第一条或最后一条记录的id来做条件筛选,再配合降序和升序获得上/下一页的结果集 。
2、限制用户翻页数量
产品实际使用过程中用户很少关心搜索结果的第1万条数据。
3、使用延迟关联
通过使用覆盖索引来查询返回需要的主键,再根据返回的主键关联原表获得需要的行,这样可以减少mysql扫描那些需要丢弃的行数。

实例:
使用索引(sex,rating)进行查询:

mysql> select <cols> from profiles inner join (
-> select <primary key cols> from profiles
-> where x.sex='m' order by rating limit 100000, 10
-> ) as x using(<primary key cols>);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网