標籤: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