服务器通过使用一个归并文件来执行排序操作,扫描待排序的表,执行如下步骤:
1)选择行直到填满排序缓冲区,
2)将缓冲区中前N行,或者(M+N行如果M指定)写入归并文件
重复上面的步骤直到扫描完全表。
新方式
sort_buffer_size 能装下[M]+N条记录,否则仍然会使用merge file,但和原方式有区别,只保存[M]+N条数据
扫描待排序的表,执行如下步骤:
1)每行按照排序要求插入队列,如果队列满了,丢弃队列中最后的一个。
2)返回队列中前N行,(如果M指定,丢弃前M行,返回接下来的N行)
这种排序方式能在时间复杂度为N的时间里完成排序,前提是排序队列
优缺点:比较耗cpu,每行都会进行一次有序队列的插入操作,耗cpu。但省内存
参考
http://www.javacoder.cn/?p=37
http://hcymysql.blog.51cto.com/5223301/1358543
http://dev.mysql.com/doc/refman/5.6/en/limit-optimization.html
SELECT ... FROM single_table ... ORDER BY non_index_column [DESC] LIMIT [M,]N;
That type of query is common in web applications that display only a few rows from a larger result set. For example:
SELECT col1, ... FROM t1 ... ORDER BY name LIMIT 10; SELECT col1, ... FROM t1 ... ORDER BY RAND() LIMIT 15;
The sort buffer has a size of sort_buffer_size. If the sort elements for N rows are small enough to fit in the sort buffer (M+N rows if M was specified), the server can avoid using a merge file and perform the sort entirely in memory by treating the sort buffer as a priority queue:
-
Scan the table, inserting the select list columns from each selected row in sorted order in the queue. If the queue is full, bump out the last row in the sort order.
-
Return the first N rows from the queue. (If M was specified, skip the first M rows and return the next N rows.)
Previously, the server performed this operation by using a merge file for the sort:
-
Scan the table, repeating these steps through the end of the table:
-
Select rows until the sort buffer is filled.
-
Write the first N rows in the buffer (M+N rows if M was specified) to a merge file.
-
-
Sort the merge file and return the first N rows. (If M was specified, skip the first M rows and return the next N rows.)