记录盲盒项目SQL错误的事故

文章目录
  1. 1. 上下文
  2. 2. 错误mapper.xml
  3. 3. 解析错误SQL
  4. 4. 总结
  5. 5. MySQL IFNULL()

记录盲盒抽奖项目因为SQL错误

导致表中数据被批量修改的问题

上下文

需要根据 is_big_prize 是否大奖字段,修改删除状态。

如果is_big_prize = ‘1’ 则修改所有大奖商品delete_status=1

如果 is_big_prize 不等于 1,则修改所有小奖商品delete_status=1

错误mapper.xml

<update id="deleteBySkuId" parameterType="com.jd.jr.bcs.domain.entity.eggMachine.LdEggmachineProduct">
UPDATE ld_eggmachine_product
<set>
modified_user = #{modifiedUser,jdbcType=VARCHAR},
modified_date = #{modifiedDate,jdbcType=TIMESTAMP},
<if test="deleteStatus != null">
delete_status = #{deleteStatus,jdbcType=INTEGER},
</if>
</set>
where
delete_status = 0
and sku_id = #{skuId,jdbcType=VARCHAR}
and activity_id = #{activityId,jdbcType=INTEGER}
<choose>
<when test="isBigPrize !=null and isBigPrize == 1">
and is_big_prize = '1'
</when>
<otherwise>
and is_big_prize is null or is_big_prize != '1'
</otherwise>
</choose>
</update>

解析错误SQL

select *
from ld_eggmachine_product
where delete_status = 1
and sku_id = '5309709'
and activity_id = 6
and is_big_prize is null
or is_big_prize != '1';

or 导致ld_eggmachine_product表中is_big_prize字段!='1'的数据都被修改

总结

is_big_prize != '1'查询不出为 NULL 的数据

select *
from ld_eggmachine_product
where is_big_prize != '1';

查询is_big_prize不等于1的正确写法,可以查询出 != ‘1’ 和 != null 的数据

select *
from ld_eggmachine_product
where delete_status = 1
and sku_id = '5309709'
and activity_id = 6
and ifnull(is_big_prize, '') != '1';

MySQL IFNULL()

IFNULL() 函数用于判断第一个表达式是否为 NULL,如果为 NULL 则返回第二个参数的值,如果不为 NULL 则返回第一个参数的值

语法:

IFNULL(expression, alt_value)

如果第一个参数的表达式 expression 为 NULL,则返回第二个参数的备用值