large skip
在为数据分页时,一般要skip多少记录并limit多少记录,例如在MySQL中:
SELECT * FROM large_table ORDER BY `id` LIMIT 10000, 30
这个过程是很慢的,因为数据库需要从第一个记录开始扫描到第10000个记录,这个比较耗时。
在http://idning.github.io/point-large-skip.html对上面的sql代码总结了两个优化方法:
方法1:
SELECT t.*
FROM (
SELECT id
FROM large_table
ORDER BY
id
LIMIT 10000, 30
) q
JOIN large_table t
ON t.id = q.id
方法2:
SELECT * FROM large WHERE id > 10000 ORDER BY id LIMIT 30
方法2有个问题,如果数据库中没有id为12的记录,那么方法2得到的结果和预期是不一样的
同样,在mongodb中也有类似的问题,一个比较好的解决方法和上面的MySQL的方法2基本相同。
count
另外,count()查询也有较慢的问题,优化方法如下:
方法1: Try COUNT(ID) instead of COUNT(*), where ID is an indexed column that has no NULLs in it. That may run faster.
方法2: If you‘re storing the binary data of the files in the longblob, your table will be massive, which will slow things down.
方法3:MySQL使用MyISAM索引,其内置了一个计数器。
参考: http://idning.github.io/point-large-skip.html
http://stackoverflow.com/questions/7228169/slow-pagination-over-tons-of-records-in-mongo
http://stackoverflow.com/questions/10764187/mongo-db-skip-takes-too-long-time
http://stackoverflow.com/questions/15402141/mysql-query-very-slow-count-on-indexed-column
http://xue.uplook.cn/database/mysqlsjk/2835.html
原文:http://my.oschina.net/letiantian/blog/324076