ON DUPLICATE KEY UPDATE 附带更新条件

来源:互联网 发布:linux sqlite3 安装 编辑:程序博客网 时间:2024/06/05 22:42

ON DUPLICATE KEY UPDATE 

1、根据表索引唯一性,如果在insert时冲突则改为update;实际场景使用中update时可能会需要一定的条件限制,但ON DUPLICATE KEY UPDATE不支持使用where关键字,可用IF关键字,使用方法如下:

 <insert id="checkInOrUpdate">        INSERT INTO rf_phase_flow(        customer_jdpin,        phase,        status,        sub_phase,        sub_status,        created_date,        modified_date        ) VALUES (        #{customerJdpin},        #{phase},        #{status},        #{subPhase},        #{subStatus},        now(),        now()        ) ON DUPLICATE KEY UPDATE        sub_phase = IF(status = 'PROC', #{subPhase} , sub_phase),        sub_status = IF(status = 'PROC', #{subStatus} , sub_status),        modified_date = IF(status = 'PROC', now() , modified_date),        status = IF(status = 'PROC', #{status} , status)    </insert>

  

注意:对于update的条件,如上为status='PROC',如果在update时会更新该值,需要将该值置为最后一个更新;

在sql执行时会首先更新了这个字段之后再执行之后的语句,这会导致永远只更新这个字段,后面的字段再检查条件时已经不满足了;


2、一般场景下ON DUPLICATE KEY UPDATE使用场景为:

  

 <insert id="saveOrUpdate">        INSERT INTO rf_phase_flow(        customer_jdpin,        phase,        status,        created_date,        modified_date        ) VALUES (        #{customerJdpin},        #{phase},        #{status},        now(),        now()        ) ON DUPLICATE KEY UPDATE        <if test="status != null">status = #{status},</if>        modified_date = now()    </insert>

3、ON DUPLICATE KEY UPDATE中关于自增id不连续

http://blog.csdn.net/zhanh1218/article/details/21459297

0 0
原创粉丝点击