Encountered in the work of 99% SQL optimization, this can give you a solution (II)

-- 示例表
CREATE TABLE `employees` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
  `age` int(20) NOT NULL DEFAULT '0' COMMENT '年龄',
  `position` varchar(20) NOT NULL DEFAULT '' COMMENT '职位',
  `hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '入职时间',
  PRIMARY KEY (`id`),
  KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE,
  KEY `idx_age` (`age`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=136326 DEFAULT CHARSET=utf8 COMMENT='员工表'

Order by and Group by optimizing

EXPLAIN select * from employees WHERE name='LiLei' and position='dev' order by age;

Using the leftmost prefix rule: immediate field can not be broken, so the query uses the name index, from key_len = 74 can also be seen, age index column used in the sorting process, since the Extra field without using filesort.

EXPLAIN select * from employees WHERE name='LiLei'  order by position;


Explain the results from the execution of view: key_len = 74, a query using the name index, since a position for sorting, Age skipped, appeared Using filesort.

EXPLAIN select * from employees WHERE name='LiLei'  order by age,position;

Find only used the index name, age and position for sorting, no Using filesort.

EXPLAIN select * from employees WHERE name='LiLei'  order by position,age;

And on a case different is that, Extra emerged Using filesort, because the order of the index is created as name, age, position, but when sorting age and position upside down position.

EXPLAIN select * from employees WHERE name='LiLei'  order by age asc, position desc;

While the sorting order of index field and the joint is the same, and is the default order by ascending, descending position desc here, leading to a different sort of index to produce Using filesort. Mysql8 version has more than descending indexes can support this type of query.

EXPLAIN select * from employees WHERE name in('LiLei', 'zhuge')  order by age, position ;

For ordering, multiple equal conditions are also a range query.

EXPLAIN select * from employees WHERE name > 'a' order by name;

Can be optimized with a covering index

EXPLAIN select name,age,position from employees WHERE name > 'a' order by name;

Sort filesort

EXPLAIN select * from employees where name='LiLei' order by position;

This view corresponds to trace sql results (only show sorting section):

set session optimizer_trace="enabled=on",end_markers_in_json=on; ‐‐开启trace
select * from employees where name = 'LiLei' order by position;
select * from information_schema.OPTIMIZER_TRACE;

{
      "join_execution": {  --sql执行阶段
        "select#": 1,
        "steps": [
          {
            "filesort_information": [
              {
                "direction": "asc",
                "table": "`employees`",
                "field": "position"
              }
            ] /* filesort_information */,
            "filesort_priority_queue_optimization": {
              "usable": false,
              "cause": "not applicable (no LIMIT)"
            } /* filesort_priority_queue_optimization */,
            "filesort_execution": [
            ] /* filesort_execution */,
            "filesort_summary": {  --文件排序信息
              "rows": 1,  --预计扫描行数
              "examined_rows": 1,  --参与排序的行
              "number_of_tmp_files": 0, --使用临时文件的个数,这个值为0代表全部使用sort_buffer内存排序,否则使用磁盘文件排序
              "sort_buffer_size": 200704,  --排序缓存的大小
              "sort_mode": "<sort_key, additional_fields>"  --排序方式,这里用的单路排序
            } /* filesort_summary */
          }
        ] /* steps */
      } /* join_execution */
    }

修改max_length_for_sort_data=10

set max_length_for_sort_data = 10;  --employees表所有字段长度总和肯定大于10字节
select * from employees where name = 'LiLei' order by position;
select * from information_schema.OPTIMIZER_TRACE;

{
      "join_execution": {
        "select#": 1,
        "steps": [
          {
            "filesort_information": [
              {
                "direction": "asc",
                "table": "`employees`",
                "field": "position"
              }
            ] /* filesort_information */,
            "filesort_priority_queue_optimization": {
              "usable": false,
              "cause": "not applicable (no LIMIT)"
            } /* filesort_priority_queue_optimization */,
            "filesort_execution": [
            ] /* filesort_execution */,
            "filesort_summary": {
              "rows": 1,
              "examined_rows": 1,
              "number_of_tmp_files": 0,
              "sort_buffer_size": 53248,
              "sort_mode": "<sort_key, rowid>"  --排序方式为双路排序
            } /* filesort_summary */
          }
        ] /* steps */
      } /* join_execution */
    }

Compare the two sorting mode, single sort field data will need to query all sort_buffer are put in, and will only sort dual primary key id field and the need to sort the sort sort_buffer into, and then through the primary key id back to the original table lookup field data needed. MySQL is controlled by the parameter max_length_for_sort_data sorting, sorting using different modes in different settings, so as to enhance the efficiency of the sort.

Optimization summary

  • Mysql support sorting filesort and index in two ways, using index refers to the complete sequencing Mysql scanning the index itself. Index high efficiency, low filesort efficiency.
  • order by satisfying two conditions will be used using index.
    order by statement to use the leftmost forefront index.
    Where clause and order by clause conditions combined to meet the leftmost column index forefront.
  • Try to complete the ordering in the index column, follow the indexing leftmost prefix rule (order of the index was created) time.
  • If the condition is not in order by the column index, will produce using filesort.

I'm not concerned about the number of the public?

  • Sweep end the two-dimensional code number [of public concern Xiaoqiang advanced road] can receive as follows:
  • Learning materials: 1T Video Tutorial: front and rear end covers Javaweb instructional videos, machine learning / AI instructional videos, Linux system tutorial videos, IELTS video tutorials;
  • More than 100 books: containing C / C ++, Java, Python programming language must see three books, LeetCode explanations Daquan;
  • Software tools: Most software includes almost you might use in programming the road;
  • Project Source: 20 JavaWeb source projects.
    Advanced small strong way two-dimensional code

Guess you like

Origin www.cnblogs.com/xiaoqiang-code/p/11495359.html