数据库是mysql,attackrecord ,attackdtail_sort两个数据记录表,数据量都较大,router_if字典表,数据量较小。为什么方法一的效率会比方法二低许多倍?
方法一、
select t2.Id Id,t2.BaseLineId,t2.BaselineName,t2.Bid,t2.Type,t2.StartTime,t2.EndTime,t2.Bps,t2.Pps,t2.Status,t2.DetailTable,t3.RouterIp,t3.IfIndex  
FROM attackdtail_sort t1 ,
(select * from attackrecord t where t.StartTime >= 1201017600281 and t.StartTime <= 1201104000281 ) t2, 
(select RouterIp,IfIndex, Id AS rid  from router_if) t3where t1.AttackId = t2.Id  and    t1.ReportKey='dstIp' and t1.ReportKeyValue = '5.5.5.100' 
and t2.Bid = t3.rid     
order by StartTime DESC  
方法二、SELECT * from attackrecord   t1,
 (select AttackId  from
  attackdtail_sort t 
  where
  t.ReportKey='dstIp' and t.ReportKeyValue = '5.5.5.100' ) t2
   where t1.StartTime >= 1201017600281 and  t1.StartTime <= 1201104000281 and t1.Id=t2.AttackId   order by StartTime DESC

解决方案 »

  1.   

    你用explain命令看看你的语句所查的rows。
      

  2.   

    感觉上那些t1,t2,t3连表的时候是不用索引的,所以连接时都会把t1,t2,t3全部检索一次。
    第二个只连了t1,t2,如果t1,t2连表时检索了n行,那么t1,t2,t3连表就连了 n*t3的行数 那么多行,就算你的t3很少也是有影响的,关键是索引用不到。
    你把explain的结果贴出来看看。
      

  3.   

    我写个sql语句,你试试看,会不会更快:SELECT   *   from   attackrecord       t1 join
      (select   AttackId     from 
        attackdtail_sort   t   
        where 
        t.ReportKey='dstIp'   and   t.ReportKeyValue   =   '5.5.5.100'   )   t2 
        on t1.Id=t2.AttackId where   t1.StartTime   > =   1201017600281   and     t1.StartTime   <=   1201104000281       order   by   StartTime   DESC
      

  4.   

    开始结贴,attackrecord   ,attackdtail_sort两个表的数据量都是约8000条。
    方法一耗时:16.59s
    方法二耗时:0.20s
    4楼方法耗时:0.20s
    感觉4楼方法和我的方法二没有区别。不知道数据量大的时候会不会有大的差别,偶对数据库还不怎么精通。
    感谢各位讨论!