一個文章庫,裏面有兩個表: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秒左右spa
解決方案:
建一個索引: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.0261it