sql - SQL限制对另一个表的引用次数而不锁定
问题描述
有没有一种技术可以避免锁定一行但仍然能够限制另一个表中引用它的行数?
例如:
create table accounts (
id integer,
name varchar,
max_users integer
);
create table users (
id integer,
account_id integer,
email varchar
);
如果我想使用max_users
. accounts
是否有另一种方法来确保并发调用不会在不锁定组行的情况下创建超过允许的用户数?
这样的事情是行不通的,因为select count(*)...
即使计数刚刚达到限制,这发生在两个并发事务中也可能是真的:
begin;
insert into users(id, account_id, email)
select 1, 1, 'john@abc.com' where (select count(*) from users where account_id = 1) < (select max_users from accounts where id = 1);
commit;
以下工作有效,但我遇到的性能问题主要是基于等待锁定的事务:
begin;
select id from accounts where id = 1 for update;
insert into users(id, account_id, email)
select 1, 1, 'john@abc.com' where (select count(*) from users where account_id = 1) < (select max_users from accounts where id = 1);
commit;
编辑:奖励问题:如果值没有存储在数据库中,但您可以动态设置怎么办?
解决方案
推荐阅读
- r - R: ggplot 在聚类分析后可视化每个聚类中的所有变量
- microcontroller - 使用 Lauterbach for Multicore 控制器在启动时设置断点失败
- vega-lite - 在 Vega-lite 中画笔放大 X 和 Y
- ios - ios - 如果太长,Eureka ActionSheetRow 选项文本会折叠
- c# - 恢复数据visual studio2019
- javascript - Javascript XMLHttpRequest 和 Jquery $.ajax 都返回当前页面的 HTML 代码
- c# - 使用 IList 查看模型
添加数据失败 - r - 使用 httr 构建带有逗号分隔查询参数的 URL
- c# - Add-Migration 在 asp.net 核心中不起作用
- python - selenium 在选择 ID/XPATH 时检索错误