mysql记录存在就更新不存在就插入

判断记录是否存在,不存在就执行插入语句,存在就执行更新语句mysql

以下例子sql

$result = mysql_query('select * from xxx where id = 1');
$row = mysql_fetch_assoc($result);
if($row){
mysql_query('update ...');
}else{
mysql_query('insert ...');
}

这样的写法有两个缺点
一、效率太差,每次执行都要执行2个sql
二、高并发的状况下数据会出问题
怎么解决这个问题呢?
mysql提供了insert … on duplicate key update的语法,若是insert的数据会引发惟一索引(包括主键索引)的冲突,即这个惟一值重复了,则不会执行insert操做,而执行后面的update操做
测试一下并发

create table test(
id int not null primary key,
num int not null UNIQUE key,
tid int not null
)

为了测试两个惟一索引都冲突的状况,而后插入下面的数据高并发

insert into test values(1,1,1), (2,2,2);

而后执行:测试

insert into test values(1,2,3) on duplicate key update tid = tid + 1;

由于a和b都是惟一索引,插入的数据在两条记录上产生了冲突,然而执行后只有第一条记录被修改fetch