【发布时间】:2015-08-19 05:02:33
【问题描述】:
我一直在搞乱分页系统的查询性能,以使数据选择尽可能快,但我遇到了一些我不太明白的事情。据我所知,当使用带有偏移量的限制时,MySQL 必须遍历偏移量之前的每一行,然后丢弃它们,因此理论上,偏移量为 10,000 的查询会比没有偏移量的查询慢得多,这通常是正确的像这种情况
select SQL_NO_CACHE * from `customers` where `NetworkID`='\func uuid()'
order by `DateTimeAdded` desc limit 0, 100;
/* finishes in 2.497 seconds */
select SQL_NO_CACHE * from `customers` where `NetworkID`='\func uuid()'
order by `DateTimeAdded` desc limit 10000, 100;
/* finishes in 2.702 seconds */
但是,如果我使用内连接将表连接到自身,并且仅使用 UserID 列进行排序和限制,则偏移量为 10,000 的速度始终快,而不是没有偏移量,这完全难倒我。这里的例子是
select SQL_NO_CACHE * from `customers`
inner join (select `UserID` from `customers` where `NetworkID`='\func uuid()'
order by `DateTimeAdded` desc limit 100)
as `Results` using(`UserID`)
/* finishes in 1.133 seconds */
select SQL_NO_CACHE * from `customers`
inner join (select `UserID` from `customers` where `NetworkID`='\func uuid()'
order by `DateTimeAdded` desc limit 10000, 100)
as `Results` using(`UserID`)
/* finishes in 1.120 seconds */
为什么使用偏移量的查询总是比不使用偏移量的查询快?
解释:
我在此处发布了一个 Google 文档电子表格,其中包含 explains 内容 here
注意:以上测试是在 PHP 循环中完成的,每次循环 20 次
注意2:customers 是视图,而不是基表
【问题讨论】:
-
尝试不同的偏移量,看看你是否得到相同的趋势。可能是这个特定的偏移量有一个非常简单的连接
-
我有,如果我用 30,000 甚至 30,000 执行此操作,它仍然始终比没有偏移量的查询快
-
optimize这个表,看看是不是一样(先中和所有未知因素) -
@Brian Leishman:我想知道您是否总是以相同的顺序运行这两个查询以进行测试。
-
也想到了@a1ex07,如果我切换查询的顺序,有偏移的还是赢
标签: mysql performance inner-join limit offset