MySQL中索引和UNION ALL的使用

來源:互聯網
上載者:User

MySQL描述:

一個文章庫,裡面有兩個表:category和article。category裡面有10條分類資料。article裡面有20萬條。article裡面有一個”article_category”欄位是與category裡的”category_id”欄位相對應的。article表裡面已經把 article_category字義為了索引。資料庫大小為1.3G。

問題描述:

  1. SELECT * FROM `article` WHERE article_category=11 ORDER BY article_id DESC LIMIT 5 。  

執行時間大約要5秒左右

解決方案:

建一個索引:

  1. create index idx_u on article (article_category,article_id);   
  2.   SELECT * FROM `article` WHERE article_category=11 ORDER BY article_id DESC LIMIT 5  
減少到0.0027秒
繼續問題: Java代碼
  1. SELECT * FROM `article` WHERE article_category IN (2,3) ORDER BY article_id DESC LIMIT 5  

執行時間要11.2850秒。

使用OR:  

Java代碼
  1. select * from article   
  2.   where article_category=2  
  3.   or article_category=3  
  4.   order by article_id desc   
  5.   limit 5  

  執行時間:11.0777

  解決方案:避免使用in 或者 or (or會導致掃表),使用union all
  使用UNION ALL:
Java代碼

  1. (select * from article where article_category=2 order by article_id desc limit 5)   
  2.   UNION ALL (select * from article where article_category=3 order by article_id desc limit 5)   
  3.   ORDER BY article_id desc limit 5  
執行時間:0.0261

聯繫我們

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