Mysql expain 及優化記錄(索引)

某次優化記錄:

操作記錄 operation_alarm 2000萬條數據

CREATE TABLE `operation_alarm` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `shop_id` bigint(20) NOT NULL,
  `shop_name` varchar(501) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `create_time` datetime NOT NULL,
  `modify_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=2914 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作記錄表';

需要檢索shop_id 4260, 某個時間段的記錄

select count(*) from operation_alarm where create_time >= date("2020-02-23") and create_time <= date("2020-03-23") and shop_id=4260;

explain看一下

type:ALL  全表掃描。給create_time加索引

alter table operation_alarm add index create_time_idx(create_time);

重新select

select count(*) from operation_alarm where create_time >= date("2020-02-23") and create_time <= date("2020-03-23") and shop_id=4260;

沒啥變化,重新explain

還是全表掃描,去掉shop_id測試一下

explain  select count(*) from operation_alarm where create_time >= date("2020-02-23") and create_time <= date("2020-03-23");

命中索引了,改Sql語句

explain  select * from operation_alarm where create_time >= date("2020-02-23") and create_time <= date("2020-03-23");

又全表掃描,這裏不知道爲什麼,先放下。把Sql改一下,縮短時間

explain  select shop_id from operation_alarm where create_time >= date("2020-03-22") and create_time <= date("2020-03-23");

又命中索引了。網上搜索了一下,找到2個,可能是因爲:

1.優化器優化成全表掃描取決與使用最好索引查出來的數據是否超過表的30%的數據。

2.在查詢數據條數約佔總條數五分之一以下時能夠使用到索引,但超過20%時,則使用全表掃描了。

給shop_id加索引

alter table operation_alarm add index create_time_idx(create_time);

查看錶索引命令:show index from operation_alarm;

重新select

select count(*) from operation_alarm where create_time >= date("2020-02-23") and create_time <= date("2020-03-23") and shop_id=4260;

索引命中了,這裏type是ref,索引性能排序(從低到高)ALL,index,range,ref,eq_ref,const,system,NULL

TODO:這裏是否應該用聯合索引?

告一段落

 

參考資料:

後端程序員必備:書寫高質量SQL的30條建議

MySQL Explain詳解

MySQL索引優化看這篇文章就夠了!

MySQL 索引及優化實戰(轉載自蒲葦 CSDN技術頭條)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章