Home  >  Article  >  Database  >  mysql limit大偏移的一个可能的优化方法_MySQL

mysql limit大偏移的一个可能的优化方法_MySQL

WBOY
WBOYOriginal
2016-06-01 13:31:09831browse

bitsCN.com

mysql limit大偏移的一个可能的优化方法

 

mysql limit 语句在大数据量时候,limit后的偏移量过大,第一次查询会特别慢,因为mysql默认是开启查询缓存的,所以,对于第二次再次执行大偏移查询不会有影响。

 

示例:100万的一个表,id做主键,auto_increment。

 

需要查询:

SELECT * FROM table ORDER BY id DESC LIMIT 990000,100

 

 

比较慢。

 

常见的办法是:

SELECT * FROM table WHERE id >=(SELECT id FROM table ORDER BY id DESC LIMIT 990000,1) ORDER BY id DESC LIMIT 100

 

 

id可能不连续,而且排序也可能不是只依赖于id, 这种办法基本上无法在实际项目中应用。

 

比如,我们的实际项目中,有排序非常复杂的方式:

ORDER BY (column1 + column2) * column3 DESC
,等等这些方式,一百万的数据,如果偏移量990000,那么反过来的排序应该更接近头部:

 

-------------------------------------------------------------------[99万-|100条]--100万

 

需要实现:

SELECT * FROM table ORDER BY columns DESC LIMIT 990000, 100

 

 

推测出一种解决办法:反向排序,然后截取头部,再次反向,得到结果:

 

$head = max(100万-99万-100,  0 );SELECT * FROM (SELECT * FROM table ORDER BY columns ASC LIMIT $head, 100 ) AS t ORDER BY columns DESC

 

 

优化完成,对于靠近末尾的,速度和开头的一样快,但如果取中间的偏移量,则没有差别。

 

bitsCN.com
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn