一个sql tuning的例子

今天同事遇到一个mysql语句执行慢的问题,叫我帮忙看看,具体语句如下:

select Products.ProductID,Name from Products 
where Products.ProductID in
(
 select ProductID from Price 
  INNER JOIN vendors ON (price.VendorID = vendors.VendorID)
 where (  price.ExpiryDate > now() or YEAR(Price.ExpiryDate) = 1 )
  and vendors.Status = ‘1′ 
  and
Price.MemberID=@memberID and Price.Disable=’false’ and IsHistory=0
)
and Disable=’false’

他说单独执行括号内的子查询,速度很快,没有那个子查询速度也很快,但合并起来后速度就很慢!

由于是mysql,对怎么查看其执行计划不熟,但单看这个语句,就可以看出问题在哪里:

在这个语句里,之所以要有in的子查询,是为了得到这个product的name,那既然是为了这个目的,为什么不用内连接去实现呢?用in的话就有可能导致索引失效,从而导致执行很慢,于是建议改成如下语句:

select Products.ProductID,Product.Name
 from Products
  INNER JOIN Price  ON Products.ProductID = Price.ProductID
  INNER JOIN vendors ON (price.VendorID = vendors.VendorID)
 where (  price.ExpiryDate > now() or YEAR(Price.ExpiryDate) = 1 )
  and vendors.Status = ‘1′ 
  and
Price.MemberID=@memberID and Price.Disable=’false’ and IsHistory=0
  and Products.Disable=’false’

结果执行速度快了N个数量级。

从这里也可以看出,SQL Tuning很大一部分在于仔细分析业务需求,然后才能写出好的sql语句。

  
« expdp时出现UDE-00008            Home            小赌怡情,大赌伤身 »

No Comments

Be the first to comment on this entry.

Leave a comment

Name(required)
Mail (will not be published)(required)
Website

Fields in bold are required. Email addresses are never published or distributed.

Some HTML code is allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
URLs must be fully qualified (eg: http://www.dbifan.com),and all tags must be properly closed.

Line breaks and paragraphs are automatically converted.

Please keep comments relevant. Off-topic, offensive or inappropriate comments may be edited or removed.

    搜索本站

    站点日历

    2月 2008
    « 1   3 »
     123
    45678910
    11121314151617
    18192021222324
    2526272829  

    订阅本站

    文章分类

    最新日志

    热点文章

    日志存档

    常用标签