【轉】mysql in語句最佳化

來源:互聯網
上載者:User

標籤:

mysql會對sql語句做最佳化, in 後面的條件不超過一定數量仍然會使用索引。
mysql 會根據索引長度和in後麵條件數量判斷是否使用索引。


另外,如果是in後面是子查詢,則不會使用索引。


一個文章庫,裡面有兩個表:category和article。category裡面有10條分類資料。article裡面有 20萬條。article裡面有一個"article_category"欄位是與category裡的"category_id"欄位相對應的。 article表裡面已經把 article_category字義為了索引。資料庫大小為1.3G。
問題描述:
執行一個很普通的查詢:

 Select * FROM `article` Where article_category=11 orDER BY article_id DESC LIMIT 5 

//執行時間大約要5秒左右

解決方案:
建一個索引:

create index idx_u on article (article_category,article_id);
Select * FROM `article` Where article_category=11 orDER BY article_id DESC LIMIT 5

 減少到0.0027秒

繼續問題:

Select * FROM `article` Where article_category IN (2,3) orDER BY article_id DESC LIMIT 5 

執行時間要11.2850秒。
使用OR:

select * from articlewhere article_category=2or article_category=3order by article_id desclimit 5

執行時間:11.0777
解決方案:避免使用in 或者 or (or會導致掃表),使用union all

使用UNION ALL:

(select * from article where article_category=2 order by article_id desc limit 5)UNION ALL (select * from article where article_category=3 order by article_id desc limit 5)orDER BY article_id desclimit 5

執行時間:0.0261

【轉】mysql in語句最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.