今天在工作中暴露一個問題,。提出優(yōu)化方案。
原sql:
SELECT batchno, g.name goodsname, '開通產(chǎn)品' opercontent, date_format(str_to_date(t1.createtime,'%Y%m%d%H%i%s'),'%Y-%m-%d %H:%i:%s') createtime, count(*) allcount, ( SELECT count(*) FROM be_channelbathorder t2 WHERE t2.errcode in ('0000','2003') AND t2.batchno = t1.batchno ) succount, ( SELECT count(*) FROM be_channelbathorder t2 WHERE t2.errcode not in ('0000','2003') AND t2.batchno = t1.batchno ) errcount, status, isNow FROMbe_channelbathorder t1,be_goods g
where 1=1 and t1.buycode=g.ID
GROUP BY batchno, t1.buycode, t1.createtimeORDER BY t1.createtime DESC
在數(shù)據(jù)量小的時候無法察覺其查詢速度。當(dāng)主表數(shù)據(jù)到達(dá)7萬時,發(fā)現(xiàn)此查詢速度及其慢至卡死。
上面經(jīng)過測試,在紅色字體部分是導(dǎo)致查詢緩慢的最主要原因。經(jīng)過查閱資料也未能找到合適方法,后來問了組內(nèi)高端人士,得知,count() 函數(shù)中可以放入分組查詢的條件。
得知后,進(jìn)行優(yōu)化:
count( case when t1.errcode='0000' OR t1.errcode='2003' then 1 else null end ) succount, count( case when t1.errcode <> '0000' AND t1.errcode <> '2003' then 1 else null end ) errcount,
優(yōu)化sql以后,減少了不必要的二次自表查詢。用explain觀察也發(fā)現(xiàn),前后兩者的確不同,速度有質(zhì)的變化。
以下是兩個 explain的比較
新聞熱點
疑難解答
圖片精選