xiaowei-blog

导航

mysql如何实现插入时如果不存在则插入如果存在则更新的操作?

 

在Oracle中有merge into来实现记录已存在就更新的操作,mysql没有merge into语法,但是有replace into的写法,同样实现记录已存在就更新的操作。 SQL Server中的实现方法是:

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

MySQL replace into 有三种形式:

1. replace into tbl_name(col_name, …) values(…)

2. replace into tbl_name(col_name, …) select …

3. replace into tbl_name set col_name=value, …

其中 “into” 关键字可以省略,不过最好加上 “into”,这样意思更加直观。另外,对于那些没有给予值的列,MySQL 将自动为这些列赋上默认值。

 

posted on 2014-11-09 22:34  xiaowei-blog  阅读(397)  评论(0编辑  收藏  举报

欢 迎 大 家光 临 我 的 个 人 博 客 !