ON DUPLICATE KEY UPDATE 附带更新条件

来源:互联网 发布:ecshop分销系统源码 编辑:程序博客网 时间:2024/06/01 09:11

ON DUPLICATE KEY UPDATE 

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

[java] view plain copy
  1. <insert id="checkInOrUpdate">  
  2.        INSERT INTO rf_phase_flow(  
  3.        customer_jdpin,  
  4.        phase,  
  5.        status,  
  6.        sub_phase,  
  7.        sub_status,  
  8.        created_date,  
  9.        modified_date  
  10.        ) VALUES (  
  11.        #{customerJdpin},  
  12.        #{phase},  
  13.        #{status},  
  14.        #{subPhase},  
  15.        #{subStatus},  
  16.        now(),  
  17.        now()  
  18.        ) ON DUPLICATE KEY UPDATE  
  19.        sub_phase = IF(status = 'PROC', #{subPhase} , sub_phase),  
  20.        sub_status = IF(status = 'PROC', #{subStatus} , sub_status),  
  21.        modified_date = IF(status = 'PROC', now() , modified_date),  
  22.        status = IF(status = 'PROC', #{status} , status)  
  23.    </insert>  

  

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

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


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

  

[java] view plain copy
  1. <insert id="saveOrUpdate">  
  2.        INSERT INTO rf_phase_flow(  
  3.        customer_jdpin,  
  4.        phase,  
  5.        status,  
  6.        created_date,  
  7.        modified_date  
  8.        ) VALUES (  
  9.        #{customerJdpin},  
  10.        #{phase},  
  11.        #{status},  
  12.        now(),  
  13.        now()  
  14.        ) ON DUPLICATE KEY UPDATE  
  15.        <if test="status != null">status = #{status},</if>  
  16.        modified_date = now()  
  17.    </insert>  

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

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

原创粉丝点击