MySQL ORDER BY主鍵id加LIMIT限制走錯(cuò)索引

背景及現(xiàn)象

  • report_product_sales_data表數(shù)據(jù)量2800萬(wàn)故俐;
  • 經(jīng)測(cè)試胁澳,在當(dāng)前數(shù)據(jù)量情況下鹿驼,order by主鍵id欲低,limit最大到49的時(shí)候可以用到索引report_product_sales_data_hq_code_orgz_id_index,大于49時(shí)就走PRIMARY主鍵索引畜晰。

表結(jié)構(gòu)

CREATE TABLE `report_product_sales_data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `hq_code` char(16) COLLATE utf8_unicode_ci NOT NULL COMMENT '公司編碼',
  `product_id` int(10) unsigned NOT NULL COMMENT '商品ID',
  `orgz_id` int(10) unsigned NOT NULL COMMENT '組織ID',
  `sales_num` double(16,3) NOT NULL COMMENT '銷(xiāo)售數(shù)量',
  `report_date` date NOT NULL COMMENT '報(bào)表日期',
  `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '狀態(tài): 0.未日結(jié)砾莱,1.已日結(jié)',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `report_product_sales_data_unique` (`hq_code`,`report_date`,`orgz_id`,`product_id`),
  KEY `report_product_sales_data_hq_code_orgz_id_index` (`hq_code`,`orgz_id`,`report_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='商品日營(yíng)業(yè)數(shù)據(jù)表';

Explain命令查看執(zhí)行計(jì)劃

-- 批量查詢(xún)耗時(shí)154ms
select product_id, sales_num, report_date from `report_product_sales_data` 
where `hq_code` = '000030' 
and `orgz_id` = 229 
and `product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938) 
and `report_date` > '2018-05-11' order by id desc
limit 320;
-- explain結(jié)果如下
id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  report_product_sales_data   range   report_product_sales_data_unique,report_product_sales_data_hq_code_orgz_id_index    report_product_sales_data_hq_code_orgz_id_index 55  NULL    37088   Using index condition; Using where; Using filesort
-- 批量查詢(xún)耗時(shí)397ms
select product_id, sales_num, report_date from `report_product_sales_data` 
where `hq_code` = '000030' 
and `orgz_id` = 229 
and `product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938) 
and `report_date` > '2018-05-11' 
order by `id` desc limit 10;
-- explain結(jié)果如下
id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  report_product_sales_data   index   report_product_sales_data_unique,report_product_sales_data_hq_code_orgz_id_index    PRIMARY 4   NULL    7624    Using where

開(kāi)啟優(yōu)化器跟蹤查看MySQL優(yōu)化過(guò)程

-- 開(kāi)啟優(yōu)化器跟蹤
set session optimizer_trace='enabled=on';
-- 在執(zhí)行完查詢(xún)語(yǔ)句后,在執(zhí)行以下的select語(yǔ)句可以查看具體的優(yōu)化器執(zhí)行過(guò)程
select * from information_schema.optimizer_trace;
-- 對(duì)于這條走了預(yù)期report_product_sales_data_hq_code_orgz_id_index索引的查詢(xún)凄鼻,我們看下優(yōu)化器的執(zhí)行過(guò)程
select product_id, sales_num, report_date from `report_product_sales_data` 
where `hq_code` = '000030' 
and `orgz_id` = 229 
and `product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938) 
and `report_date` > '2018-05-11' order by id desc
limit 320;
-- 看下trace部分
{
  "steps": [
    {
      "join_preparation": {
        "select#": 1,
        "steps": [
          {
            "expanded_query": "/* select#1 */ select `report_product_sales_data`.`product_id` AS `product_id`,`report_product_sales_data`.`sales_num` AS `sales_num`,`report_product_sales_data`.`report_date` AS `report_date` from `report_product_sales_data` where ((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11')) order by `report_product_sales_data`.`id` desc limit 320"
          }
        ]
      }
    },
    {
      "join_optimization": {
        "select#": 1,
        "steps": [
          {
            "condition_processing": {
              "condition": "WHERE",
              "original_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11'))",
              "steps": [
                {
                  "transformation": "equality_propagation",
                  "resulting_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11') and multiple equal(229, `report_product_sales_data`.`orgz_id`))"
                },
                {
                  "transformation": "constant_propagation",
                  "resulting_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11') and multiple equal(229, `report_product_sales_data`.`orgz_id`))"
                },
                {
                  "transformation": "trivial_condition_removal",
                  "resulting_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11') and multiple equal(229, `report_product_sales_data`.`orgz_id`))"
                }
              ]
            }
          },
          {
            "table_dependencies": [
              {
                "table": "`report_product_sales_data`",
                "row_may_be_null": false,
                "map_bit": 0,
                "depends_on_map_bits": [
                ]
              }
            ]
          },
          {
            "ref_optimizer_key_uses": [
              {
                "table": "`report_product_sales_data`",
                "field": "hq_code",
                "equals": "'000030'",
                "null_rejecting": false
              },
              {
                "table": "`report_product_sales_data`",
                "field": "hq_code",
                "equals": "'000030'",
                "null_rejecting": false
              },
              {
                "table": "`report_product_sales_data`",
                "field": "orgz_id",
                "equals": "229",
                "null_rejecting": false
              }
            ]
          },
          {
            "rows_estimation": [
              {
                "table": "`report_product_sales_data`",
                "range_analysis": {
                  "table_scan": {
                    "rows": 28276082,
                    "cost": 6.14e6
                  },
                  "potential_range_indices": [
                    {
                      "index": "PRIMARY",
                      "usable": false,
                      "cause": "not_applicable"
                    },
                    {
                      "index": "report_product_sales_data_unique",
                      "usable": true,
                      "key_parts": [
                        "hq_code",
                        "report_date",
                        "orgz_id",
                        "product_id"
                      ]
                    },
                    {
                      "index": "report_product_sales_data_hq_code_orgz_id_index",
                      "usable": true,
                      "key_parts": [
                        "hq_code",
                        "orgz_id",
                        "report_date",
                        "id"
                      ]
                    }
                  ],
                  "setup_range_conditions": [
                  ],
                  "group_index_range": {
                    "chosen": false,
                    "cause": "not_group_by_or_distinct"
                  },
                  "analyzing_range_alternatives": {
                    "range_scan_alternatives": [
                      {
                        "index": "report_product_sales_data_unique",
                        "ranges": [
                          "000030 <= hq_code <= 000030 AND 2018-05-11 < report_date"
                        ],
                        "index_dives_for_eq_ranges": true,
                        "rowid_ordered": false,
                        "using_mrr": false,
                        "index_only": false,
                        "rows": 1848962,
                        "cost": 2.22e6,
                        "chosen": true
                      },
                      {
                        "index": "report_product_sales_data_hq_code_orgz_id_index",
                        "ranges": [
                          "000030 <= hq_code <= 000030 AND 229 <= orgz_id <= 229 AND 2018-05-11 < report_date"
                        ],
                        "index_dives_for_eq_ranges": true,
                        "rowid_ordered": false,
                        "using_mrr": false,
                        "index_only": false,
                        "rows": 37088,
                        "cost": 44507,
                        "chosen": true
                      }
                    ],
                    "analyzing_roworder_intersect": {
                      "usable": false,
                      "cause": "too_few_roworder_scans"
                    }
                  },
                  "chosen_range_access_summary": {
                    "range_access_plan": {
                      "type": "range_scan",
                      "index": "report_product_sales_data_hq_code_orgz_id_index",
                      "rows": 37088,
                      "ranges": [
                        "000030 <= hq_code <= 000030 AND 229 <= orgz_id <= 229 AND 2018-05-11 < report_date"
                      ]
                    },
                    "rows_for_plan": 37088,
                    "cost_for_plan": 44507,
                    "chosen": true
                  }
                }
              }
            ]
          },
          {
            "considered_execution_plans": [
              {
                "plan_prefix": [
                ],
                "table": "`report_product_sales_data`",
                "best_access_path": {
                  "considered_access_paths": [
                    {
                      "access_type": "ref",
                      "index": "report_product_sales_data_unique",
                      "rows": 1.85e6,
                      "cost": 1.82e6,
                      "chosen": true
                    },
                    {
                    //可以看到選擇report_product_sales_data_hq_code_orgz_id_index這個(gè)索引時(shí)cost最小
                      "access_type": "ref",
                      "index": "report_product_sales_data_hq_code_orgz_id_index",
                      "rows": 37088,
                      "cost": 44506,
                      "chosen": true
                    },
                    {
                      "access_type": "range",
                      "rows": 27816,
                      "cost": 51924,
                      "chosen": false
                    }
                  ]
                },
                "cost_for_plan": 44506,
                "rows_for_plan": 37088,
                "chosen": true
              }
            ]
          },
          {
            "attaching_conditions_to_tables": {
              "original_condition": "((`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11'))",
              "attached_conditions_computation": [
                {
                  "access_type_changed": {
                    "table": "`report_product_sales_data`",
                    "index": "report_product_sales_data_hq_code_orgz_id_index",
                    "old_type": "ref",
                    "new_type": "range",
                    "cause": "uses_more_keyparts"
                  }
                }
              ],
              "attached_conditions_summary": [
                {
                  "table": "`report_product_sales_data`",
                  "attached": "((`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11'))"
                }
              ]
            }
          },
          {
            "clause_processing": {
              "clause": "ORDER BY",
              "original_clause": "`report_product_sales_data`.`id` desc",
              "items": [
                {
                  "item": "`report_product_sales_data`.`id`"
                }
              ],
              "resulting_clause_is_simple": true,
              "resulting_clause": "`report_product_sales_data`.`id` desc"
            }
          },
          {
            "refine_plan": [
              {
                "table": "`report_product_sales_data`",
                "pushed_index_condition": "((`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`report_date` > '2018-05-11'))",
                "table_condition_attached": "(`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938))",
                "access_type": "range"
              }
            ]
          },
          {
            "reconsidering_access_paths_for_index_ordering": {
            //到了order by id這邊時(shí)腊瑟,MySQL也沒(méi)有改變執(zhí)行計(jì)劃,還是選擇了report_product_sales_data_hq_code_orgz_id_index索引
              "clause": "ORDER BY",
              "index_order_summary": {
                "table": "`report_product_sales_data`",
                "index_provides_order": false,
                "order_direction": "undefined",
                "index": "report_product_sales_data_hq_code_orgz_id_index",
                "plan_changed": false
              }
            }
          }
        ]
      }
    },
    {
      "join_execution": {
        "select#": 1,
        "steps": [
          {
            "filesort_information": [
              {
                "direction": "desc",
                "table": "`report_product_sales_data`",
                "field": "id"
              }
            ],
            "filesort_priority_queue_optimization": {
              "limit": 320,
              "rows_estimate": 61044633,
              "row_size": 76,
              "memory_available": 262144,
              "chosen": true
            },
            "filesort_execution": [
            ],
            "filesort_summary": {
              "rows": 321,
              "examined_rows": 15768,
              "number_of_tmp_files": 0,
              "sort_buffer_size": 26964,
              "sort_mode": "<sort_key, additional_fields>"
            }
          }
        ]
      }
    }
  ]
}
-- 對(duì)于這條走了非預(yù)期PRIMARY主鍵索引的查詢(xún)块蚌,我們看下優(yōu)化器的執(zhí)行過(guò)程
select product_id, sales_num, report_date from `report_product_sales_data` 
where `hq_code` = '000030' 
and `orgz_id` = 229 
and `product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938) 
and `report_date` > '2018-05-11' order by id desc
limit 10;
-- 看下trace部分
{
  "steps": [
    {
      "join_preparation": {
        "select#": 1,
        "steps": [
          {
            "expanded_query": "/* select#1 */ select `report_product_sales_data`.`product_id` AS `product_id`,`report_product_sales_data`.`sales_num` AS `sales_num`,`report_product_sales_data`.`report_date` AS `report_date` from `report_product_sales_data` where ((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11')) order by `report_product_sales_data`.`id` desc limit 10"
          }
        ]
      }
    },
    {
      "join_optimization": {
        "select#": 1,
        "steps": [
          {
            "condition_processing": {
              "condition": "WHERE",
              "original_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11'))",
              "steps": [
                {
                  "transformation": "equality_propagation",
                  "resulting_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11') and multiple equal(229, `report_product_sales_data`.`orgz_id`))"
                },
                {
                  "transformation": "constant_propagation",
                  "resulting_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11') and multiple equal(229, `report_product_sales_data`.`orgz_id`))"
                },
                {
                  "transformation": "trivial_condition_removal",
                  "resulting_condition": "((`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11') and multiple equal(229, `report_product_sales_data`.`orgz_id`))"
                }
              ]
            }
          },
          {
            "table_dependencies": [
              {
                "table": "`report_product_sales_data`",
                "row_may_be_null": false,
                "map_bit": 0,
                "depends_on_map_bits": [
                ]
              }
            ]
          },
          {
            "ref_optimizer_key_uses": [
              {
                "table": "`report_product_sales_data`",
                "field": "hq_code",
                "equals": "'000030'",
                "null_rejecting": false
              },
              {
                "table": "`report_product_sales_data`",
                "field": "hq_code",
                "equals": "'000030'",
                "null_rejecting": false
              },
              {
                "table": "`report_product_sales_data`",
                "field": "orgz_id",
                "equals": "229",
                "null_rejecting": false
              }
            ]
          },
          {
            "rows_estimation": [
              {
                "table": "`report_product_sales_data`",
                "range_analysis": {
                  "table_scan": {
                    "rows": 28276082,
                    "cost": 6.14e6
                  },
                  "potential_range_indices": [
                    {
                      "index": "PRIMARY",
                      "usable": false,
                      "cause": "not_applicable"
                    },
                    {
                      "index": "report_product_sales_data_unique",
                      "usable": true,
                      "key_parts": [
                        "hq_code",
                        "report_date",
                        "orgz_id",
                        "product_id"
                      ]
                    },
                    {
                      "index": "report_product_sales_data_hq_code_orgz_id_index",
                      "usable": true,
                      "key_parts": [
                        "hq_code",
                        "orgz_id",
                        "report_date",
                        "id"
                      ]
                    }
                  ],
                  "setup_range_conditions": [
                  ],
                  "group_index_range": {
                    "chosen": false,
                    "cause": "not_group_by_or_distinct"
                  },
                  "analyzing_range_alternatives": {
                    "range_scan_alternatives": [
                      {
                        "index": "report_product_sales_data_unique",
                        "ranges": [
                          "000030 <= hq_code <= 000030 AND 2018-05-11 < report_date"
                        ],
                        "index_dives_for_eq_ranges": true,
                        "rowid_ordered": false,
                        "using_mrr": false,
                        "index_only": false,
                        "rows": 1848962,
                        "cost": 2.22e6,
                        "chosen": true
                      },
                      {
                        "index": "report_product_sales_data_hq_code_orgz_id_index",
                        "ranges": [
                          "000030 <= hq_code <= 000030 AND 229 <= orgz_id <= 229 AND 2018-05-11 < report_date"
                        ],
                        "index_dives_for_eq_ranges": true,
                        "rowid_ordered": false,
                        "using_mrr": false,
                        "index_only": false,
                        "rows": 37088,
                        "cost": 44507,
                        "chosen": true
                      }
                    ],
                    "analyzing_roworder_intersect": {
                      "usable": false,
                      "cause": "too_few_roworder_scans"
                    }
                  },
                  "chosen_range_access_summary": {
                    "range_access_plan": {
                      "type": "range_scan",
                      "index": "report_product_sales_data_hq_code_orgz_id_index",
                      "rows": 37088,
                      "ranges": [
                        "000030 <= hq_code <= 000030 AND 229 <= orgz_id <= 229 AND 2018-05-11 < report_date"
                      ]
                    },
                    "rows_for_plan": 37088,
                    "cost_for_plan": 44507,
                    "chosen": true
                  }
                }
              }
            ]
          },
          {
            "considered_execution_plans": [
              {
                "plan_prefix": [
                ],
                "table": "`report_product_sales_data`",
                "best_access_path": {
                  "considered_access_paths": [
                    {
                      "access_type": "ref",
                      "index": "report_product_sales_data_unique",
                      "rows": 1.85e6,
                      "cost": 1.82e6,
                      "chosen": true
                    },
                    {
                    //可以看到選擇report_product_sales_data_hq_code_orgz_id_index這個(gè)索引時(shí)cost最小
                      "access_type": "ref",
                      "index": "report_product_sales_data_hq_code_orgz_id_index",
                      "rows": 37088,
                      "cost": 44506,
                      "chosen": true
                    },
                    {
                      "access_type": "range",
                      "rows": 27816,
                      "cost": 51924,
                      "chosen": false
                    }
                  ]
                },
                "cost_for_plan": 44506,
                "rows_for_plan": 37088,
                "chosen": true
              }
            ]
          },
          {
            "attaching_conditions_to_tables": {
              "original_condition": "((`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11'))",
              "attached_conditions_computation": [
                {
                  "access_type_changed": {
                    "table": "`report_product_sales_data`",
                    "index": "report_product_sales_data_hq_code_orgz_id_index",
                    "old_type": "ref",
                    "new_type": "range",
                    "cause": "uses_more_keyparts"
                  }
                }
              ],
              "attached_conditions_summary": [
                {
                  "table": "`report_product_sales_data`",
                  "attached": "((`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938)) and (`report_product_sales_data`.`report_date` > '2018-05-11'))"
                }
              ]
            }
          },
          {
            "clause_processing": {
              "clause": "ORDER BY",
              "original_clause": "`report_product_sales_data`.`id` desc",
              "items": [
                {
                  "item": "`report_product_sales_data`.`id`"
                }
              ],
              "resulting_clause_is_simple": true,
              "resulting_clause": "`report_product_sales_data`.`id` desc"
            }
          },
          {
            "refine_plan": [
              {
                "table": "`report_product_sales_data`",
                "pushed_index_condition": "((`report_product_sales_data`.`orgz_id` = 229) and (`report_product_sales_data`.`hq_code` = '000030') and (`report_product_sales_data`.`report_date` > '2018-05-11'))",
                "table_condition_attached": "(`report_product_sales_data`.`product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938))",
                "access_type": "range"
              }
            ]
          },
          {
            "reconsidering_access_paths_for_index_ordering": {
            //到了order by id這邊時(shí)闰非,MySQL改變了執(zhí)行計(jì)劃,選擇了PRIMARY主鍵索引
              "clause": "ORDER BY",
              "index_order_summary": {
                "table": "`report_product_sales_data`",
                "index_provides_order": true,
                "order_direction": "desc",
                "disabled_pushed_condition_on_old_index": true,
                "index": "PRIMARY",
                "plan_changed": true,
                "access_type": "index_scan"
              }
            }
          }
        ]
      }
    },
    {
      "join_execution": {
        "select#": 1,
        "steps": [
        ]
      }
    }
  ]
}

現(xiàn)象及修改方案

  1. 通過(guò)現(xiàn)象可以看到MySQL在order by 主鍵id時(shí)峭范,limit值的大小達(dá)到了某個(gè)臨界值后财松,改變了執(zhí)行計(jì)劃,選擇了主鍵索引纱控,但不知道具體的規(guī)則究竟是怎樣辆毡。
  2. 既然如此,就不用order by id這個(gè)clause甜害,改為order by report_date舶掖,因?yàn)閕d和report_date的大小是正相關(guān)的,而且可以走到report_product_sales_data_hq_code_orgz_id_index索引尔店,換了個(gè)法子解決了當(dāng)前這個(gè)問(wèn)題眨攘。
explain select product_id, sales_num, report_date from `report_product_sales_data` 
where `hq_code` = '000030' 
and `orgz_id` = 229 
and `product_id` in (11453,11472,11487,11446,11456,12088,11433,114170,11479,11491,11485,11482,70672,68998,154298,11435,11481,11515,122573,167938) 
and `report_date` > '2018-05-11' 
order by `report_date` desc limit 10;
id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  report_product_sales_data   range   report_product_sales_data_unique,report_product_sales_data_hq_code_orgz_id_index    report_product_sales_data_hq_code_orgz_id_index 55  NULL    37088   Using index condition; Using where

總結(jié)

  • 在order by id的情況下主慰,MySQL由于自身的優(yōu)化器選擇,為了避免某些排序的消耗期犬,可能會(huì)走非預(yù)期的PRIMARY主鍵索引河哑;
  • order by 和 limit 結(jié)合使用,如果where 字段龟虎,order by字段都是索引,那么有l(wèi)imit索引會(huì)使用order by字段所在的索引沙庐,沒(méi)有l(wèi)imit會(huì)使用where 條件的索引鲤妥;
  • 對(duì)于數(shù)據(jù)量比較大,而且執(zhí)行量很高的分頁(yè)sql拱雏,盡可能將所有的查詢(xún)字段包括在索引中棉安,同時(shí)使用索引來(lái)消除排序;
  • 多用explain查看是否使用到了最優(yōu)索引铸抑;
  • 利用optimizer trace查看優(yōu)化器執(zhí)行過(guò)程贡耽;
  • 觀察mysql的slow_query_log,及時(shí)做排查優(yōu)化鹊汛。

參考鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市刁憋,隨后出現(xiàn)的幾起案子滥嘴,更是在濱河造成了極大的恐慌,老刑警劉巖至耻,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件若皱,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡尘颓,警方通過(guò)查閱死者的電腦和手機(jī)走触,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)疤苹,“玉大人互广,你說(shuō)我怎么就攤上這事√荡撸” “怎么了兜辞?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)夸溶。 經(jīng)常有香客問(wèn)我逸吵,道長(zhǎng),這世上最難降的妖魔是什么缝裁? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任扫皱,我火速辦了婚禮足绅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘韩脑。我一直安慰自己氢妈,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布段多。 她就那樣靜靜地躺著首量,像睡著了一般。 火紅的嫁衣襯著肌膚如雪进苍。 梳的紋絲不亂的頭發(fā)上加缘,一...
    開(kāi)封第一講書(shū)人閱讀 51,727評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音觉啊,去河邊找鬼拣宏。 笑死,一個(gè)胖子當(dāng)著我的面吹牛杠人,可吹牛的內(nèi)容都是我干的勋乾。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼嗡善,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼辑莫!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起滤奈,我...
    開(kāi)封第一講書(shū)人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤摆昧,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后蜒程,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體绅你,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年昭躺,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了忌锯。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡领炫,死狀恐怖偶垮,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情帝洪,我是刑警寧澤似舵,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站葱峡,受9級(jí)特大地震影響砚哗,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜砰奕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一蛛芥、第九天 我趴在偏房一處隱蔽的房頂上張望提鸟。 院中可真熱鬧,春花似錦仅淑、人聲如沸称勋。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)赡鲜。三九已至,卻和暖如春庐船,著一層夾襖步出監(jiān)牢的瞬間蝗蛙,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工醉鳖, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人哮内。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓盗棵,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親北发。 傳聞我的和親對(duì)象是個(gè)殘疾皇子纹因,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 一、SQL速成 結(jié)構(gòu)查詢(xún)語(yǔ)言(SQL)是用于查詢(xún)關(guān)系數(shù)據(jù)庫(kù)的標(biāo)準(zhǔn)語(yǔ)言琳拨,它包括若干關(guān)鍵字和一致的語(yǔ)法瞭恰,便于數(shù)據(jù)庫(kù)元件...
    shadow雨軒閱讀 514評(píng)論 0 3
  • 轉(zhuǎn) # https://www.cnblogs.com/easypass/archive/2010/12/ 08/...
    呂品?閱讀 9,732評(píng)論 0 44
  • MySQL不權(quán)威總結(jié) 歡迎閱讀 本文并非事無(wú)巨細(xì)的mysql學(xué)習(xí)資料,而是選擇其中重要狱庇、困難惊畏、易錯(cuò)的部分進(jìn)行系統(tǒng)地...
    liufxlucky365閱讀 2,591評(píng)論 0 26
  • 一、MySQL架構(gòu)與歷史 A.并發(fā)控制 1.共享鎖(shared lock密任,讀鎖):共享的颜启,相互不阻塞的 2.排他...
    ZyBlog閱讀 19,837評(píng)論 3 177
  • 推送證書(shū)導(dǎo)出P12是也許你會(huì)遇到 無(wú)法找打P12的選項(xiàng)如圖改成這樣就搞定了 當(dāng)然 你也許還會(huì)發(fā)現(xiàn) 這個(gè)里面沒(méi)有你...
    健健鍋閱讀 5,491評(píng)論 3 7