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

2.处理方案
2.1>
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>
组装会员卡列表信息,将每个会员卡的卡类型进行设置
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>
总结
到此这篇关于mysql中update按照多重条件进行更新处理的文章就介绍到这了,更多相关mysql>










