1. 程式人生 > >MYSQL索引的使用(使用UNION ALL代替OR)

MYSQL索引的使用(使用UNION ALL代替OR)

 一個文章庫,裡面有兩個表: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