mysql - 索引,in,or等優化


mysql

一個文章庫,里面有兩個表: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 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:
(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.0261


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM