首页 > 解决方案 > 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;

编辑:奖励问题:如果值没有存储在数据库中,但您可以动态设置怎么办?

标签: sqlpostgresql

解决方案


推荐阅读