多个api接口同时对单表c_point表更新创建数据,
c_point表结构:
id primary key int(11) auto incrment,
uid char(32) not null unique key,
temporary decimal(10,2) not null,
pressure decimal(10,2) not null,
updated_at timestamp not null default current_timestamp on update current_timestamp
计算规则:
uid = md5(deviceid+pointid)
接口a:
更新c_point表的temporary字段,如果没有则创建一条新纪录。
接口b:
更新c_point表的pressure,如果没有则创建一条新纪录。
接口a、b在插入前都有select检查。
当a、b接口同时调用时出现a和b同时进行insert操作,报出
exception 'pdoexception' with message 'sqlstate[23000]: integrity constraint violation: 1062 duplicate entry '8b3e94ae3568001854dd7c112702dd36' for key 'uid'
针对这种多个接口针对同一个表的同一个row创建更新时怎么处理,能让两个接口都更新各自的字段?
结论:
1)插入前先select,再insert(目前的场景不合适,但仍然有必要加上去)
2)try catch 解析错误码
$duplicate = false; $entry = $key = null; $inner = $e->getinner(); $info = $inner->errorinfo; // check if mysql error is for a duplicate key if (in_array($info[1], array(1062, 1022, 1558))) { $duplicate = true; preg_match(/'(.*)'.*'(.*)'/, $info[2], $matches); $entry = $matches[1]; $key = $matches[2]; }
3)insert ignore
4) on duplicate key
具体问题需要具体分析
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/
回复内容: 环境:mysql5.6、php5.5
多个api接口同时对单表c_point表更新创建数据,
c_point表结构:
id primary key int(11) auto incrment,
uid char(32) not null unique key,
temporary decimal(10,2) not null,
pressure decimal(10,2) not null,
updated_at timestamp not null default current_timestamp on update current_timestamp
计算规则:
uid = md5(deviceid+pointid)
接口a:
更新c_point表的temporary字段,如果没有则创建一条新纪录。
接口b:
更新c_point表的pressure,如果没有则创建一条新纪录。
接口a、b在插入前都有select检查。
当a、b接口同时调用时出现a和b同时进行insert操作,报出
exception 'pdoexception' with message 'sqlstate[23000]: integrity constraint violation: 1062 duplicate entry '8b3e94ae3568001854dd7c112702dd36' for key 'uid'
针对这种多个接口针对同一个表的同一个row创建更新时怎么处理,能让两个接口都更新各自的字段?
结论:
1)插入前先select,再insert(目前的场景不合适,但仍然有必要加上去)
2)try catch 解析错误码
$duplicate = false; $entry = $key = null; $inner = $e->getinner(); $info = $inner->errorinfo; // check if mysql error is for a duplicate key if (in_array($info[1], array(1062, 1022, 1558))) { $duplicate = true; preg_match(/'(.*)'.*'(.*)'/, $info[2], $matches); $entry = $matches[1]; $key = $matches[2]; }
3)insert ignore
4) on duplicate key
具体问题需要具体分析
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/
不需要使用 select 检查。直接插,冲突了就表明已经存在了,按已经存在的逻辑做。
ps: 请认真排版你的问题好不好,刚刚因为排版不清晰看错了。
