码迷,mamicode.com
首页 > 数据库 > 详细

MySQL调优 ---- IN

时间:2015-08-08 06:47:06      阅读:181      评论:0      收藏:0      [点我收藏+]

标签: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

标签:mysql   优化   in   join   性能   

原文地址:http://blog.csdn.net/wenniuwuren/article/details/47350469

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!