Mysql expain 及優化記錄(索引)

2021-10-04 02:55:08 字數 2741 閱讀 4526

某次優化記錄:

操作記錄 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, 某個時間段的記錄

explain看一下

type:all  全表掃瞄。給create_time加索引

alter table operation_alarm add index create_time_idx(create_time);
重新select

沒啥變化,重新explain

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

explain  select count(*) from operation_alarm where create_time >= date("2020-02-23") and create_time <= date("2020-03-23");
命中索引了,改sql語句

又全表掃瞄,這裡不知道為什麼,先放下。把sql改一下,縮短時間

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

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

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

給shop_id加索引

alter table operation_alarm add index create_time_idx(create_time);
檢視表索引命令:show index from operation_alarm;

重新select

索引命中了,這裡type是ref,索引效能排序(從低到高)all,index,range,ref,eq_ref,const,system,null

todo:這裡是否應該用聯合索引?

告一段落

MySQL 優化更新記

1 適當新增索引,索引過多在修改刪除時,索引自身維護需要花費更長時間 2 insert批量插入 3 不用 查詢的列,列出來 4 更小的資料型別通常更好,應該盡量使用最小資料型別,因為它們占用更少的磁碟,記憶體和cpu快取,並且所需要的cpu週期也更少 5 簡單資料型別,通常需要更少的cpu 週期。例...

記bitmap記憶體優化

減小bitmap佔記憶體大小的方案有兩種 1,options.insamplesize 設定取樣率的值,原理是等比縮放寬高。縮放多少倍bitmap的記憶體大小占用久縮放多少倍。2.options.inpreferredconfig bitmap.config.rgb 565 設定位深,也可以說是設定...

CloudFlare CDN折騰記 優化設定

近期又在折騰了,常訪問我部落格的朋友或許頁面曾出現過502錯誤提示,那是折騰cloudflare cdn不成功的提示。在此先感謝罈子,在他的執著和求真之下,昨天晚上終於成功使用上cloudflare cdn。之前設定好cloudflare cdn出現的502錯誤這個問題至今找不到原因,反正罈子讓我重...