今天在工作中暴露一个问题,。提出优化方案。
原sql:
SELECTbatchno,
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
FROM
be_channelbathorder t1,be_goods g
where 1=1 and t1.buycode=g.ID
GROUP BY
batchno,
t1.buycode,
t1.createtime
ORDER 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的比较