mysql中使用replace into

发布时间 2023-06-20 17:38:16作者: 周文豪

replace into是insert into的增强版。在向表中插入数据时,我们经常会遇到这样的情况:1、首先根据主键或者唯一索引判断数据是否存在;2、如果不存在,则插入;3、如果存在,则更新。

MySQL 中如何实现这样的逻辑呢?MySQL 中有更简单的方法: replace into

replace into t(id, update_time) values(1, now());
或
replace into t(id, update_time) select 1, now();

replace into相当于

if not exists (select 1 from t where id = 1) 
insert into t(id, update_time) values(1, now()) 
else 
update t set update_time = now() where id = 1

 如果表中的一个旧记录与一个用于PRIMARY KEY或一个UNIQUE索引的新记录具有相同的值,则在新记录被插入之前,旧记录被删除。

使用REPLACE INTO,必须拥有表的INSERT和DELETE权限。

在xml文件中使用replace into语句

<insert id="updateOrInsertClientInfo" useGeneratedKeys="true" keyProperty="BM" parameterType="list" >
    replace into bm_kh
    (<include refid="Base_Column_List"/>)
    VALUES
    <foreach collection="list" item="it" separator=",">
    ( #{it.bm},#{it.mc},#{it.jm},
      #{it.sjbm},#{it.kjm},#{it.sh},
      #{it.dzdh},#{it.jwbz},#{it.yhzh},
      #{it.yjdz},#{it.bz},#{it.yskm},
      #{it.dqbm},#{it.dqmc},#{it.dqkm},
      #{it.sfzjy},#{it.wj},#{it.xfsh},
      #{it.xfzfjh}
    )
    </foreach>
  </insert>