Understand the sorting principle and optimization of mysql_order by

1. Sorting algorithm
   a. One-time scanning performance is high, reducing the number of random io requests
   b. The sorting operation is performed in the memory (sort_buffer), first select the result and then sort, if the result value is greater than max_length_for_sort_data The threshold setting needs two times io read
    c. The associated query will generate a temporary table and then order by.

2. Optimization ideas
   a. Minimize io read max_length_for_sort_data threshold setting
   b. Try to use ordered sorting output. Use covering index, primary key index c    .
   Control the number of select fields, no need to input fields that are      not      needed Sorting, if the sort_buffer is small, a temporary table is generated, and   a sorting scan or a secondary sorting scan is used to store the sorting result in the temporary table, depending on the parameters: max_length_for_sort_data   If the value is greater than the value set by max_length_for_sort_data, a secondary scan is used.    Two parameters: max_length_for_sort_data: Determine which scanning strategy to use sort_buffer: Determine whether a temporary table needs to be created to store the sorted results during the sorting process. shared by each thread. two scan algorithm












     1), take out the sorting field and row pointer information according to the conditions
     2), sort in the sort_buffer, if the sort_buffer is small, generate a temporary table, store the sorting result in the temporary table
     3), go to the main index structure according to the row number of the sorting result Get data
For example : select * from t where filed='abc' order by field2
             This statement will go through 2 scans
             for the first time to search for eligible records
             and the second time to get the field according to the row number
           If there is an index on the field field, parse Rule: use index, Using filesort
           If there is no index on the field field, the parsing rule: Using where; Using filesort
Description: order by has nothing to do with index; (except covering index)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326282877&siteId=291194637