为了获得相同的数据集,以下两个SQL花费了不同的时间:
1, Select * from user where id between 100,000 and 200,000. (took 0.05 second)
2, Select * from user oder by id ASC limit 100,000,100,000. (took 3 seconds)
Note: the id is primary key.
为什么第二个sql这么慢,我认为id是主键,所以排序应该非常快,甚至mysql也不需要对它进行排序,因为主键已经排序了。它只需要直接在B +树的叶子节点中寻找正确的位置。时间应为O(1)。 我猜两个sql应该是相同的速度。
Edits:
I tried to use explain on the above two SQLs. But I still can not understand
why mysql doesn't treat limit as a range query(it's already sorted).
I guess I may say:"Mysql is not a smart engine, it's kind of old!"