文章来自:
商务合作:请加沫沫2230304070
特色文章正文
在开发过程中,我们经常会用到分页。 核心技术是使用limit来读取数据。 在使用limit进行寻呼测试时,得到如下数据:
select * from news order by id desc limit 0,10
耗时0.003秒
select * from news order by id desc limit 10000,10
耗时0.058秒
select * from news order by id desc limit 100000,10
耗时0.575秒
select * from news order by id desc limit 1000000,10
耗时7.28秒
我们惊讶地发现,在数据量较大的情况下,mysql的分页阈值越大,查询速度就越慢。 从100万条开始查询速度已经需要7秒。 这对我们来说是不可接受的价值!
改善计划1
select * from news
where id > (select id from news order by id desc limit 1000000, 1)
order by id desc
limit 0,10
查询时间0.365秒,效率提升尤为显着! ! 原则是什么? ? ?
我们使用条件来过滤id。 在子查询(selectidfromnewsorderbyiddesclimit1000000,1)中php 分页查询,我们只查询id数组,相比select *或者select多个数组节省了大量的查询开销!
改善计划2
适合id连续的系统,速度极快!
select * from news
where id between 1000000 and 1000010
order by id desc
它不适合有条件和不连续id的查询。 非常快!
百万数据页的注意事项
继续上一节,我们添加查询条件:
select id from news
where cate = 1
order by id desc
limit 500000 ,10
查询时间20秒
这是多么可怕的速度啊! ! 借助内部解决方案进行优化:
select * from news
where cate = 1 and id > (select id from news where cate = 1 order by id desc limit 500000,1 )
order by id desc
limit 0,10
查询时间15秒
优化的疗效并不显着,但是条件的影响还是很大的! 在这种情况下,无论我们如何优化sql语句,都无法解决运行效率的问题。
我们换个思路:建立一个索引表,只记录文章的id和分类信息,我们对文章内容这个大数组进行划分。
表news2[文章表引擎myisam字符集utf-8]
--------------------------------------------------
idint11字段手动降低
cateint11 索引
写入数据时同步两张表,如果查询成立,则可以使用news2进行条件查询:
select * from news
where cate = 1 and id > (select id from news2 where cate = 1 order by id desc limit 500000,1 )
order by id desc
limit 0,10
请注意,条件 id> 之前使用了 news2 表!
运行时间为 1.23 秒,我们可以看到运行时间减少了近 20 倍! ! 当数据在10万条左右时,查询时间可以保持在0.5秒左右,这是一个我们只能逐渐忍受的值!
然而,一秒对于服务器来说仍然是一个不可接受的值! ! 还有其他方法可以优化吗? ?
我们尝试了一个很大的变化:
将news2的存储引擎改为innodb,执行结果惊人!
select * from news
where cate = 1 and id > (select id from news2 where cate = 1 order by id desc limit 500000,1 )
order by id desc
limit 0,10
只需要0.2秒,非常好的速度。
至此,我们的页面优化就完成了,其实是非常有效的。 你可以自己测试一下!
以上就是本文的全部内容php 分页查询,希望对您的学习有所帮助,也希望您支持php自学中心