sql语句优化之delete
原始版删除单个或多个数据
dao层接⼝写法
/**
* 基于记录id执⾏删除业务(有些公司,记录不会
* 直接删除,⽽是在删除时修改其状态)
* @param ids
* @return rows
*/
int deleteObjects(@Param("ids")ids);
接下来是⼏种sql对⽐
下⾯写法是原始状态,如果传⼊0或null需要注意
<delete id="deleteObjects">
delete from sys_logs
where id in
<foreach collection="ids"
open="("
close=")"
separator=","
item="id">
#{id}
</foreach>
</delete>
下⾯写法避免了null和0的情况
<delete id="deleteObjects">
delete from sys_logs
<if test="ids ==null || ids.length == 0">
where id=-1
</if>
<if test="ids !=null and ids.length>0">
where ids in
<foreach collection="ids"
open="("
sql语句优化方式
close=")"
separator=","
item="id">
#{id}
</foreach>
</if>
</delete>
⾸先分析⼀下,in或not in⼀般避免使⽤,效率慢,那么改版如下
这样避免使⽤in但是传⼊null和0,负数还是不⾏
<delete id="deleteObjects">
delete from sys_logs
<!--相当于 where id=1 or id=2 or id=3-->
<where>
<foreach collection="ids"
separator="or"
item="id">
id=#{id}
</foreach>
</where>
</delete>
那么可以这样优化
要么执⾏when,要么then之后的-1
<delete id="deleteObjects">
delete from sys_logs
<where>
<choose>
<when test="ids!=null and ids.length>0">
<foreach collection="ids"
separator="or"
item="id">
id=#{id}
</foreach>
</when>
<otherwise>
id=-1
</otherwise>
</choose>
</where>
</delete>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。