Mysql最佳化小技巧

來源:互聯網
上載者:User

標籤:全表掃描   頻繁   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最佳化小技巧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.