同样的查询结果,为什么效率相差十倍?该怎么解决

同样的查询结果,为什么效率相差十倍?

数据库是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) t3

where 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



感觉上那些t1,t2,t3连表的时候是不用索引的,所以连接时都会把t1,t2,t3全部检索一次。

第二个只连了t1,t2,如果t1,t2连表时检索了n行,那么t1,t2,t3连表就连了 n*t3的行数 那么多行,就算你的t3很少也是有影响的,关键是索引用不到。

你把explain的结果贴出来看看。




我写个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

同样的查询结果,为什么效率相差十倍?该怎么解决

相关文章:

你感兴趣的文章:

标签云: