• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mysql 搞代码 7年前 (2018-05-31) 245次浏览 已收录 0个评论

同样的查询结果,为什么效率相差十倍?
数据库是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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:同样的查询结果,为什么效率相差十倍?该怎么解决

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址