mysql批量更新

例如我们平时使用mysql的批量更新都是这样的

    <foreach collection="list" item="p" index="index" separator=";">
        UPDATE product_third_code_mapping
        SET stock_num = #{p.stockNum},
        update_time = NOW()
        WHERE source_channel = #{p.channelCode}
        AND third_product_code = #{p.skuId}
    </foreach>

但是这样的sql会影响效率
所以我们需要结合case when then else end来进行优化

 UPDATE product
        SET third_merchant_product_code = ( CASE
        <foreach collection="poList" item="p" separator=" ">
            WHEN id = #{p.storeProductId} then #{p.thirdProductCode}
        </foreach>
        ELSE 0 END )
        WHERE
        is_deleted = 0
        AND id IN (
        <foreach collection="idsList" item="p" separator=",">
            #{p}
        </foreach>
        )

如果需要更新多个字段

   update im_virtual_channel_stock iv
        set iv.virtual_stock_num = (
        case
        <foreach collection="poList" item="p" separator="   ">
            when iv.item_id = #{p.storeProductId} then #{p.stockNum}
        </foreach>
        else 0 end
        ),
        iv.virtual_available_stock_num = (
        case
        <foreach collection="poList" item="p" separator="   ">
            when iv.item_id = #{p.storeProductId} then #{p.stockNum} - iv.freeze_stock_num
        </foreach>
        else 0 end
        )
        where iv.is_available=1
        and iv.is_deleted=0
        and iv.item_id in (
        <foreach collection="poList" item="p" separator=",">
            #{p.storeProductId}
        </foreach>
        )
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值