sql语句优化之delete

本文探讨了SQL语句中删除数据的优化方法,避免使用`IN`或`NOT IN`操作符以提高效率。通过提供不同写法的对比,包括处理`NULL`和`0`值的特殊情况,提出了更优的解决方案,以确保在各种输入情况下都能执行高效的删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原始版删除单个或多个数据
dao层接口写法

/**
	   * 基于记录id执行删除业务(有些公司,记录不会
	   * 直接删除,而是在删除时修改其状态)
	   * @param ids
	   * @return rows
	   */
	  int deleteObjects(@Param("ids")Integer...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="("
                  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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值