参考:mysql分页优化 大家都知道分页肯定会用到这两种类型的sql: (1) select count(*) from table where 条件 (2) select * from table where 条件 (页码数-1)*每页数 当数据量一大(几百w),不管你是用什么存储引擎,这两种sql都会很恶心了。 对于
参考:mysql分页优化
大家都知道分页肯定会用到这两种类型的sql:
(1) select count(*) from table where 条件
(2) select * from table where 条件 (页码数-1)*每页数
当数据量一大(几百w),不管你是用什么存储引擎,这两种sql都会很恶心了。
对于第一种:
我表示无解,如果你单表几百万、几千万,即使走覆盖索引也要很长时间,带了where条件,无论是myisam还是innodb都会全表扫描,如果你对结果并不是非要精确,走cache吧,因为被坑了很多次,所以我坚持分表处理,尽量保持单表不过百万。
对于第二种:
(1)首先当然是建立索引了,让查询结果在索引中进行;
(2)只返回需要的自动
(3)先获取到offset的id后,再直接使用limit size来获取数据。
随便创建了一张表,插了一百万的数据
[sql] view plaincopy
create table if not exists `article` ( `id` int(11) not null auto_increment, `category_id` int(11) not null, `name` char(16) not null, `content` text not null, primary key (`id`), ) engine=innodb default charset=utf8
看看优化效果:
[sql] view plaincopy
#查询花费 38.6875 秒 select sql_no_cache * from `article` limit 800000 , 20 #查询花费 0.9375 秒 select sql_no_cache id, category_id from `article` limit 800000 , 20 #查询花费 0.3594 秒 select sql_no_cache id, category_id from `article` where id >= (select id from `article` limit 800000 , 1) limit 20 #查询花费 0.0000 秒 select sql_no_cache id, category_id from `article` where id between 800000 and 800020
windows下测试可能存在一定误差,当然还有很多其他的方法如建立索引表等待。
最后:对于大型平台或系统,用框架啊、什么orm就行不通了,会让你尴尬的!
来源: http://www.lai18.com/content/312862.html