记得以前做项目的时候遇到了一个关于批量操作的问题,对于一批 数据 需要根据 对应主键 去判断 更新什么内容时就需要灵活的处理,如下sql (mybaits框架)
int updateInnerInstructionLineVersions(@Param("list")List<InnerInstructionLine> newVosionLine);//Mapper接口定义
<!-- Mapper.xml 文件 -->
<update id="updateInnerInstructionLineVersions" parameterType="map">
update inner_instruction_line set instruction_id = case trade_id
<foreach collection="list" index="index" item="item">
when #{item.tradeId} then #{item.instructionId}
</foreach>
end
<where>
and trade_id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item.tradeId}
</foreach>
</where>
</update>
//这句sql的意思是 更新 instruction_id 字段,如果trade_id= 参数中传过来的 #{item.tradeId} 则 instruction_id 的值为 #{item.instructionId} 。
拓展一下 case * when * 语句。 还有一些比较好用的地方, 如 排序,当查询的时候需要排序,但字段本身又不能满足时 ,例如我们要把所有待处理的 警告放在最上面 ,其他的按添加时间排序 ,但待处理的任务 状态是3 (例如状态有1、 2 、3、 4、 5等),处于中间比较尴尬,这个时候case when 就派上大用场了如下:
SELECT CreateTime,STATUS,CASE WHEN STATUS=3 THEN 0 ELSE 1 END AS a FROM alarm ORDER BY a,CreateTime DESC