【个人小结】一次数据库性能优化问题

需求场景:存在表t_result_changelog,表记录了caseNo的相关数据,有些caseNo已经被删除,但表中的数据没有对应清理。

难点分析:判断表中哪些数据已经被删除,需要在对应版本的caseInfo_version中查找

初次尝试:

选择表中所有的caseNo以及他们的cVersion

select cVersion, caseNo from t_result_changelog group by cVersion, caseNo

判断caseNo是否在对应的表中存在

select count(*) from  `tbl_caseinfo_${version}` where caseNo = #{caseNo}

删除

delete from t_result_changelog where cVersion = #{cVersion} and caseNo = #{caseNo}

耗时情况,大概1秒处理4个用例,计算了一下,处理完所有10万用例需要7个小时

修改后:

获得表中所有的cversion(因为cversion数量是少的,清理前都只有十多个)

select distinct(cVersion) from ${tableName}

选择这个cversion下,存在于t_result_changlog但不存在于对应的caseinfo表中的数据

(通过这个操作,避免之前对于所有用例的遍历判断)

select distinct(caseNo) from t_result_changelog where cVersion = #{cversion} and caseNo not in (select caseNo from tbl_caseinfo_${versionTbl})

删除

delete from t_result_changelog where caseNo in 
		<foreach item="caseNotExisted" collection="casesNotExisted" open="(" separator="," close=")">
			#{caseNotExisted}
		</foreach> 

如果版本表都不存在,直接删除

delete from t_result_changelog where cVersion = #{cVersion}

耗时21334ms

数据清理情况
  清理前 清理后
不重复用例数 105974 315
总数据条数 603407 3718

反思总结:

1. 避免不必要的操作

2. 能在一个sql里面进行完的决不拆开

猜你喜欢

转载自blog.csdn.net/VeastLee/article/details/83015075