postgresql - PostgreSQL 11 中的并发更新
问题描述
我有大约 10 个查询同时更新一行,所以我想知道两者之间有什么区别
UPDATE account SET balance = balance + 1000
WHERE id = (SELECT id FROM account
where id = 1 FOR UPDATE);
和
BEGIN;
SELECT balance FROM account WHERE id = 1 FOR UPDATE;
-- compute $newval = $balance + 1000
UPDATE account SET balance = $newval WHERE id = 1;
COMMIT;
我正在使用 PosgreSQL 11,那么正确的解决方案是什么?这两个解决方案中的多事务会发生什么?
解决方案
两个版本将具有完全相同的效果,并且都防止面对并发异常,因为行在被修改之前被锁定。
第一种方法更可取,因为只有一次客户端-服务器往返,所以事务更短,持有锁的时间更短,提高了并发性。
做到这一点并避免并发数据修改的最佳方法是:
UPDATE account
SET balance = balance + 1000
WHERE id = 1;
This does the same, because an UPDATE
automatically puts an exclusive lock on the affected row, and a blocked query will see the updated version of the row when the lock is gone.
推荐阅读
- mysql - 为什么 SQL HAVING 条件中的 COUNT 不能计算正确的值?
- artifactory - 如何将 Artifactory Permission Target 应用于 pip 和其他非人类可预测/可读的 repo?
- html - Angular ng build --prod 后,主页上的所有图像都不会显示
- reactjs - ReactJS 使用在其他 ReactDOM 上呈现的按钮更改路由
- c++ - MacOS POD 类型检查上的 C++
- java - 动画完成后如何隐藏进度条
- r - 没有模式字符串的子集字符串
- delphi - 如何使用特定的网络适配器进行连接?
- c - 强制 Accelio 使用 RDMA
- geojson - 在 GeoJSON 对象中添加 bbox 的正确方法是什么?