今天在工作中暴露一個問題,。提出優化方案。
原sql:
SELECT batchno, g.name goodsname, '開通產品' 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
在數據量小的時候無法察覺其查詢速度。當主表數據到達7萬時,發現此查詢速度及其慢至卡死。
上面經過測試,在紅色字體部分是導致查詢緩慢的最主要原因。經過查閱資料也未能找到合適方法,后來問了組內高端人士,得知,count() 函數中可以放入分組查詢的條件。
得知后,進行優化:
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,
優化sql以后,減少了不必要的二次自表查詢。用explain觀察也發現,前后兩者的確不同,速度有質的變化。
以下是兩個 explain的比較
新聞熱點
疑難解答