MySQL索引優化(索引單錶優化案例)

2022-06-16 08:30:09 字數 2682 閱讀 5512

1、單錶查詢優化

建表sql

案例#查詢 category_id 為1 且 comments 大於 1 的情況下,views 最多的 article_id。

執行sql:

#結論:很顯然,type 是 all,即最壞的情況。extra 裡還出現了 using filesort,也是最壞的情況。優化是必須的。

查詢索引:show index from article;

#開始優化:

# 1.1 新建索引+刪除索引

# 1.2 第2次explain

#結論:

#type 變成了 range,這是可以忍受的。但是 extra 裡使用 using filesort 仍是無法接受的。

#但是我們已經建立了索引,為啥沒用呢?

#這是因為按照 btree 索引的工作原理,

# 先排序 category_id,

# 如果遇到相同的 category_id 則再排序 comments,如果遇到相同的 comments 則再排序 views。

#當 comments 欄位在聯合索引裡處於中間位置時,

#因comments > 1 條件是乙個範圍值(所謂 range),

#mysql 無法利用索引再對後面的 views 部分進行檢索,即 range 型別查詢字段後面的索引無效。

# 1.3 刪除第一次建立的索引

drop index idx_article_ccv on article;

# 1.4 第2次新建索引

# 1.5 第3次explain

#結論:可以看到,type 變為了 ref,extra 中的 using filesort 也消失了,結果非常理想。

mysql 單 索引 mysql 單錶索引優化

建表語句 create table if not exists article id int 10 unsigned not null primary key auto increment,author id int 10 unsigned not null,category id int 10 u...

mysql 索引 單錶優化

索引分析 type 為 all using filesort 自己進行了排序沒有用到索引 檢視 article 表有什麼索引 show index from article 只有乙個主鍵 建立索引 where 後面的字段需要建索引,但不一定必須建。嘗試著去建 alter table 表名 add i...

Mysql之索引優化案例 單錶優化 雙表優化

單錶優化 建表create table article id int unsigned notnull primary keyauto increment author id int unsigned notnull category id int unsigned notnull views in...