在向表中插入数据的时候,经常遇到这样的情况:
1、首先判断数据是否存在;
2、如果存在,则更新; 3、如果不存在,则插入。 在 SQL Server 中可以这样写:if exists (select 1 from table where id = 1) update table set update_time = getdate() where id = 1 else insert into table(id, update_time) values(1, getdate())
先select,判断是否存在,存在则 update 否则 insert,如下
也可以这样写
if not exists (select 1 from table where id = 1) insert into table(id, update_time) values(1, getdate()) else update table set update_time = getdate() where id = 1
先select,不存在则 insert,否则 update
但在MySQL 中有更简单的方法,使用 replace into关键字replace into table(id, update_time) values(1, now()); 或
replace into table(id, update_time) select 1, now();
replace into 跟 insert 功能类似,不同点在于:replace into 会首先尝试插入数据到表中。1、如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。
2、 否则,直接插入新数据。要注意的是:插入数据的表必须有主键或者是唯一索引!否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。
而 如果是使用 insert 语句插入带有与表内数据唯一键的值重复的记录时,则会报sql错误.
MySQL中replace into有三种写法: 1. replace into table(col1, col2, ...) values(val1, val2, ...) 2. replace into table(col1, col2, ...) select val1, val2, ... 3. replace into table set col=val, ... 前两种形式用的多些。其中 into 关键字可以省略,不过最好加上 into ,这样意思更加直观。注意,当使用replace into进行更新操作时,会将原数据行先删除再执行插入动作,这是两个动作,所以受影响的行为两行,新增的行记录id会继续自增到最后面,原记录行id被删除.但这个动作在binlog文件中却只被记录成了一个 update 操作,这样在进行主从读写时,会引起id主键的冲突.参考 http://blog.csdn.net/jiao_fuyou/article/details/46485631 和http://www.cnblogs.com/monian/archive/2014/10/09/4013784.html
另外,replace into的更新操作只会将设定的字段的values值写入表中,未设定的字段值将被置为默认值,这在很多情况下与业务逻辑不符合,要谨慎使用.这种更新&插入业务可以参考使用 insert into ... on duplicate key update 语句.
同时 replace不支持update某些特性,也就不能直接当作update使用:常见update写法:update table set col=col+1 where id=1;
使用replace into不支持这样的写法:replace into table set col=col+1, id=1;1、首先判断数据是否存在;(没问题)
2、如果不存在,则插入;(没问题) 3、如果存在,某字段值在原来的基础上加上或减去某个数,如加一操作。(不支持)