MySQL調優 ---- IN

來源:互聯網
上載者:User

標籤:mysql   最佳化   in   join   效能   

  在慢查詢最佳化中, 對於 IN 這個關鍵字的最佳化的出現機率還是挺高的。 其實對於 IN 關鍵字出現的 SQL 最佳化其實難度不高, 重要的是熟悉該 SQL 的應用情境也可以說是商務邏輯。

  一、舉個最近遇到的例子( 業務: 查詢該標籤下所有的文章數量 ):
select count(*) from cms_article ca where 某個TagID in (select cat.tag_id from cms_article_tag cat where ca.id=cat.article_id)


看下 EXPLAIN 結果:

引用MySQL官方文檔的一句話:A typical case for poor  IN subquery performance is when the subquery returns a small number of rows but the outer query returns a large number of rows to be compared to the subquery result.
可以從 EXPLAIN 結果明顯看出, IN 子查詢就掃了2行, 而另一個查詢掃描了大量行數, 完全符合官方文檔說的慢查詢情況。



  二、如何最佳化呢?   本文開頭就說了, 先熟悉商務邏輯, 然後就很好改了。引用MySQL官方文檔的解決方案:The optimizer is more mature for joins than for subqueries, so in many cases a statement that uses a subquery can be executed more efficiently if you rewrite it as a join.[也就是熟悉業務, 然後大多數情況都能改成 JOIN 的方式來最佳化]
最佳化後SQL:
select count(*) from cms_article ca RIGHT JOIN cms_article_tag cat ON cna.id = cnat.article_id WHERE cnat.tag_id=某TagID



EXPLAIN結果:
查詢行數銳減, 只要25*1的複雜度就完成了本次查詢。 


  三、 參考資料
                         MySQL官網



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

MySQL調優 ---- IN

聯繫我們

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