乙個sql的優化

2021-09-22 20:39:38 字數 2201 閱讀 8421

原文:

乙個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,又提公升了一點點..

關於乙個加法優化的乙個地方

include include include base.h int main int argc,char argv,char envp 下面是彙編 01291000 55 push ebp 01291001 8bec mov ebp,esp 01291003 56 push esi 0129100...

乙個sql的例子

select dbo.userinfo.username,dbo.userinfo.usertruename,dbo.userinfo.useremail,dbo.userinfo.usermobile,dbo.userinfo.usertelephone,dbo.userinfo.usercar,...

乙個複雜的sql

select f.course node info id as nodeid,c.course node name as nodename,c.course node type as nodelevel,c.course code,case when select course node info ...