replace into学习

转自:https://blog.csdn.net/risingsun001/article/details/38977797

1.介绍 

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

作用相当于, 

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

id为主键,首先判断数据是否存在; 1. 如果不存在,则插入;2.如果存在,则更新。

但不完全相同,1. 如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。 2. 否则,直接插入新数据。【会有一个删除的操作,相当于delete+update。】

表需要有唯一索引,否则作用完全相当于insert,会重复插入数据。

REPLACE语句返回一个数来表示受影响的行数,这是删除和插入的行的总和。

 

posted @ 2022-10-08 19:55  lypbendlf  阅读(24)  评论(0)    收藏  举报