mysql查询花了太长时间来响应

时间:2015-01-08 12:52:19

标签: mysql

为什么mysql中的这种查询响应时间太长:

select s.sid,s.sname, 
   sum(case WHEN d.dgr_date='2014-12-31' then d.daily_gen end) as dgen,
   round(sum(case WHEN d.dgr_date between '2013-12-01' and last_day
   ('2013-12-31') then d.daily_gen end)/1000000,2) as pmtd
from dgrs d ,locs l, spvs s 
where l.mloc=d.mc_loc and s.sid=l.spid 
group by s.sname;


index: compound(d.dgr_date, d.daily_gen), d.mc_loc(fk:l.mloc), l.mloc, s.sid
Main table: dgrs(400k rows).

解释查询

  id    select_type table   type    possible_keys   key     key_len ref        rows  Extra
  1     SIMPLE      s       ALL     PRIMARY         NULL    NULL    NULL       20    Using temporary; Using filesort
  1     SIMPLE      l       ref     PRIMARY,fk_spid fk_spid  4      oms.s.sid   9    Using index
  1    SIMPLE       d       ref     fk_mcloc        fk_mcloc 102    oms.l.mloc  485  NULL

2 个答案:

答案 0 :(得分:1)

  1. 您应该在GROUP BY子句中使用索引字段。我猜ssid是表PK的{​​{1}}。使用它而不是spvss
  2. 确保sname子句中显示的字段已编入索引。
  3. 在列WHERE上放置一个索引,并将条件从第二个dgr_date移到where子句中:

    CASE

答案 1 :(得分:0)

mysql join可能会缩短响应时间

select s.sid,s.sname, 
   sum(case WHEN d.dgr_date='2014-12-31' then d.daily_gen end) as dgen,
   round(sum(case WHEN d.dgr_date between '2013-12-01' and last_day
   ('2013-12-31') then d.daily_gen end)/1000000,2) as pmtd
  from dgrs d 
   inner join locs l on l.mloc=d.mc_loc 
   inner join spvs s on and s.sid=l.spid
group by s.sname;