为什么这么慢的mysql查询要执行呢?

时间:2011-03-03 14:21:54

标签: mysql

select 
    'Owner' as 'Type',
    count(s.shipwynum) as Total,
    o.ownwynum as WYNum,
    o.ownshortnam as 'Short name',
    o.ownnam as 'Full name',
    cio.weburl as 'Web URL',
    count(if(s.statuscod = 'O',1,null)) as 'number of orders',
    count(if(s.statuscod = 'S',1,null)) as 'number of ships' 
from owner o 
left join ship s on o.ownwynum = s.benownwynum and s.deleted = 'N' and
      s.statuscod in ('O','S') and
      s.benownwynum != '' and s.benownwynum !='0' and s.benownwynum is not null 
left join companyinfo cio on cio.objwynum = s.benownwynum and
      cio.deleted = 'N' and cio.comflag = 'OW' where o.deleted = 'N'     
group by o.ownnam

此查询在9分55秒运行,并检索10,106条记录。

我的问题是为什么需要花费大量时间来获取数据,以及为了减少执行时间而导致的问题是什么?

但有趣的是我运行了这个查询:=

select * from ship 

执行时需要3分12秒才能获取75,672条记录。

有任何优化它的想法吗?

1 个答案:

答案 0 :(得分:3)

除非你真的有意避免s.shipwynum的空值,试试这个 - 替换:

count(s.shipwynum) as Total

count(*) as Total

通常情况下,COUNT(*)的运行速度比COUNT(表达式)快。


另一个实验,替换:

count(if(s.statuscod = 'O',1,null)) as 'number of orders'
count(if(s.statuscod = 'S',1,null)) as 'number of ships' 

sum(if(s.statuscod = 'O',1,0)) as 'number of orders'
sum(if(s.statuscod = 'S',1,0)) as 'number of ships'