一个sql的优化

系统 1348 0
原文: 一个sql的优化

目的:为了查询某天某个服务器上的登录id的个数
 
刚开始编写的sql:
select count(a.mac) logusers from Log_MacLogin_All a  
              where isMoNi != 1 
                       and loginTime <= '2015-02-01 23:59:59' and loginTime >= '2015-02-01 00:00:00'
                       and a.mac in (select mac from Inst_User_Mac b
                                                            where doTime <= '2015-01-30 23:59:59' 
                                                                    and doTime >= '2015-01-30 00:00:00   and serverKey='p1s1' );
 执行时间为:33s
对于这个sql,首先的优化点在于"in",因为测试发现in条件里面的数据差不多将近万以上的数据..
 
第一次优化:把in改为exists后,效率有一点的提升
select count(mac) logusers from Log_MacLogin_All a  
              where isMoNi != 1 
                       and loginTime <= '2015-02-01 23:59:59' and loginTime >= '2015-02-01 00:00:00'
                       and exists (select mac from Inst_User_Mac b
                                                            where doTime <= '2015-01-30 23:59:59' 
                                                                    and doTime >= '2015-01-30 00:00:00   and serverKey='p1s1'
                                                                    and a.mac = b.mac );
执行时间为:26s
 
第二次优化:在网上查了下,有的说用join会快一些。把exists改为join试试
select count(a.mac) logusers from Log_MacLogin_All   a    inner join 
(select mac from Inst_User_Mac   where doTime <= '2015-01-30 23:59:59' 
                       and doTime >= '2015-01-30 00:00:00    and serverKey='p1s1'   )    b  
                        on a.mac = b.mac 
       where a.isMoNi != 1 
                       and a.loginTime <= '2015-02-01 23:59:59' and a.loginTime >= '2015-02-01 00:00:00';
执行时间为2.6s,性能有了明显的提高啊
 
第三次优化:把>= <= 改为between and 这样会减少把数据查出来后的计算操作
select count(a.mac) logusers from Log_MacLogin_All   a    inner join 
(select mac from Inst_User_Mac   where doTime between  '2015-01-30 00:00:00  
                       and  '2015-01-30 23:59:59'   and serverKey='p1s1'   )    b  
                        on a.mac = b.mac 
       where a.isMoNi != 1 
                       and a.loginTime between 
 '2015-02-01 00:00:00'   and  '2015-02-01 23:59:59';
执行时间为2.4s,提升了0.2s
 
第四次优化:假如要查某一天的数据不如直接date_format();
select count(a.mac) logusers from Log_MacLogin_All   a   inner join 
(select mac from Inst_User_Mac   where DATE_FORMAT(doTime,'%Y%m%d')='20150130' and serverKey='p1s1'  )    b  
                        on a.mac = b.mac 
       where a.isMoNi != 1  and  DATE_FORMAT(a.loginTime,'%Y%m%d') = '20150201';
执行时间为2.36s,又提升了一点点..

一个sql的优化


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论