標籤:全表掃描 頻繁 tab 最小 通過 小技巧 mit update 就是
磁碟重組:
mysql資料一開始是在磁碟上順序存放的,如果資料表有頻繁的update改動,那麼資料就會形成很多片段,拖慢速度和不利於索引;
最佳化片段有兩種方式:
alter table user engine innodb;其實user這個表原先也是innodb的,這句話看上去沒有任何意義,但是mysql會重新規整資料
optimize table user; 也可以修複;
片段最佳化是一種很費cpu和記憶體的事,最好在夜裡執行;
非常規 的 min max 最佳化
select min(age) from table;
不管table有多少資料,這條語句都是非常快的,因為mysql內部存到有相關的值,通過explain 可以看出已經被mysql最佳化過了;
稍微改一下語句;
select min(age) from table where status=1;
通過explain 查看 是全表掃描;
mysql要一行一行的取出來看status是不是1,如果是,那對比上一次的age看看那個小;有點想冒泡排序一樣;
有個特別的最佳化方式,要在age有索引的前提下;
select min(age) from table use index(age) where status=1 limit 1;
強制mysql使用age索引,因為索引是排好序的,所以取第一個就是最小值,max同理
count非常規最佳化
select count(*) from table;
通過explain可以看出已經被mysql最佳化到常亮層級了;非常快
但是:
select count(*) from table where id>100;
速度飛速下降,explain 已檢視用到了全表掃描;從100開始掃描全表
然而這條語句是很快的,只用掃描前100條:
select count(*) from table where id<100;
所以最佳化方法是利用數學加減法:
( select count(*) from table ) - ( select count(*) from table where id<100 )
union最佳化:
串連查詢結果的時候 如非必要 盡量使用 union all,因為union all 不過濾資料,效率高,而union要過濾資料,代價很大;
Mysql最佳化小技巧