您当前的位置:易学堂 > 日志记录

mysql中update按照多重条件进行更新处理的方案

时间:2022-09-13 09:57:51

更新数据是使用数据库时最重要的任务之一,下面这篇文章主要给大家介绍了关于mysql中update按照多重条件进行更新处理的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下!

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为次数卡)。

会员卡表信息:

b2a855c6e14d7286a883c07d24e823ee_20220909160926122.png

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>
标签: mysql