【轉】mysql in語句優化

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


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


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

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

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

解決方案:
建一個索引:
sql

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 article
where article_category=2
or article_category=3
order by article_id desc
limit 5

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

使用UNION ALL:spa

(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 desc
limit 5

執行時間:0.0261code

相關文章
相關標籤/搜索