随笔 - 756  文章 - 0 评论 - 33 阅读 - 136万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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>
复制代码

 



感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接
posted on   周文豪  阅读(509)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!
点击右上角即可分享
微信分享提示