對mysql聯合索引中的欄位進行合理排序

來源:互聯網
上載者:User

標籤:strong   sp   資料   on   ad   bs   sql   mysql   table   

在MySQL的where條件中,有時會用到很多的條件,通常為了加快速度會把這些欄位放到聯合索引中,可以更快的提高搜尋速度;

但是對聯合索引中欄位順序的合理排序,便更能提高速度

例子:select * from table where (groupid=1000) and (userid=500) and (time=140012345)

建立的索引也通常很隨性的就按照where條件中欄位的順序建立 

ALTER  TABLE  table  ADD  INDEX g_u_time_index(groupid,userid,time);

那麼MySQL就會先檢索到groupid=1000的所有資料,假如搜到了1000條,再在檢索到的1000條資料中再檢索userid=500的資料,假設還剩餘300條,再在300條中搜尋time=140012345的資料,假設就剩了100條;這樣總共搜尋了1000+300+100=1400條資料才找到符合的100條

 

但是為了更好的最佳化,我們現在需要在建立索引前,對這幾個欄位進行計算,計算他們在表中所佔的比例

可以寫一個select語句來查看:計算各個條件在表中所佔的比例大小

select count(*) total,sum(groupid=1000) gtotal,sum(userid=500)  utotal,sum(time=1400123456) time  from table;

total  10000

gtotal  1000

utotal  300

time    800

可見如果先搜尋島userid=500的資料就可以剔除掉一大半,只剩下300條符合的,再在300中搜尋符合time=1400123456和groupid=1000的資料,這樣就大大縮減了查詢次數;

按照從小到大的順序排列,可以減少搜尋次數

sql改為:select * from table where  (userid=500) and (time=140012345) and (groupid=1000) 

ALTER  TABLE  table  ADD  INDEX g_u_time_index ( userid , time , groupid)

 

 

參考:《高效能MySQL》第五章建立高效能索引

 

對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.