mysql update按多重条件更新

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

mysql update按多重条件更新

卖柴火的小伙子   2022-09-29 我要评论

1.场景问题说明

mysql中一般的update写法支持的方式是,update 表 set 字段名=修改后的字段值 where 条件1 and 条件2 and 其他条件;如果现在需求是对满足where后面的条件基础之上需对满足指定的条件数据再进行不同更新处理,那应该如何处理?如果有这样的疑问或是遇到此类场景请继续往下看.

还原一下我遇到的业务场景:现有一批会员卡,会员卡类型有次数卡和期限卡之分,期限卡余额为每天扣除一天,次数卡余额不随时间进行变化,只有使用之后才会扣除。现需要对会员卡进行更新截止时间的操作,其中只需要对期限卡更新余额操作。主要问题的难点在于会员卡类型为期限卡的会员卡,不仅需要更新有效截止时间,还需要更新会员卡的余额。为方便说明问题,简化业务如下:将会员卡id为1、2、3的截止日期更新为2022-05-01 22:50:59,其中期限卡余额更新为11.次数卡余额不做处理(会员卡id为1和2为期限卡,3为次数卡)。

会员卡表信息:

2.处理方案

2.1 使用update case when

sql如下:

UPDATE staff_card SET end_time="2022-05-01 22:50:59",update_time=NOW(),
rest_count=(CASE WHEN card_type=1 THEN 11 ELSE rest_count END) WHERE id IN  (1,2,3)

配置文件写法:

 <update id="updateRestCount" >
           UPDATE staff_card
            <set>
            end_time="2022-05-01 22:50:59",update_time=NOW(),
rest_count=(CASE WHEN card_type=1 THEN 11 ELSE rest_count END)
           </set> 
            WHERE id IN  
            ( 
				<foreach collection="cardIds" item="cardId">
					#{cardId}
				</foreach>
			)  
    </update>

注意写法:只对于期限卡才更新余额,次数卡余额不更新,也就是次数卡的余额rest_count字段不进行更新,直接写ELSE rest_count,如果次数卡余额更新为其他金额,则ELSE 后面写具体的余额值.

2.2 使用if标签

组装会员卡列表信息,将每个会员卡的卡类型进行设置

  ArrayList<CardInfo> cardList= new ArrayList<>();
        CardInfo cardInfo = new CardInfo();
        // 设置会员卡id
        cardInfo.setId(1);
        // 设置会员卡类型:1.期限卡;2.次数卡
        cardInfo.setCardType(1);
        CardInfo cardInfo2 = new CardInfo();
        cardInfo2.setId(2);
        cardInfo2.setCardType(1);
        CardInfo cardInfo3 = new CardInfo();
        cardInfo3.setId(3);
        cardInfo3.setCardType(2);
        cardList.add(cardInfo);
        cardList.add(cardInfo2);
        cardList.add(cardInfo3);

mapper接口:

public interface CardMapper {
    // 更新会员卡信息
    void updateRestCount(@Param("cardList") List<CardInfo> cardInfos);
}

配置文件:

 <update id="updateRestCount" >
        <foreach collection="cardList" item="card">
            UPDATE staff_card
            <set>
               end_time="2022-05-01 22:50:59",update_time=NOW(),
                <if test="card.cardType == 1">
                    rest_count =11
                </if>
            </set>
            WHERE id=#{card.id};
        </foreach>
    </update>

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们