【发布时间】:2018-02-11 10:53:35
【问题描述】:
我想在 Postgres 10 中有一个 SQL 语句或函数,仅当行数少于一定数量时才允许我插入一行。
select count(*) from mytable where mykey = 1
--- do the following only if the above is less than 5
insert into mytable (myvalue, mykey) values ('randomvalue', 1)
--- so there are never more than 5 rows in mytable with mykey = 1
这样的伪代码是否可以在应用程序中工作(多次往返调用 postgres 服务器)?
tx = app.tx("start transaction");
count = tx.query("select count(*) from mytable where mykey = 1")
if (count < 5) {
tx.query("insert into mytable (myvalue, mykey) values ('randomvalue', 1)")
}
tx.do("commit")
如果它不起作用,我怎么能在 Postgres 端这样做,所以我只从应用程序拨打一个电话,比如select myinsertfunction('randomvalue', 1)?
无论是上面的多次往返方式,还是对 postgres 的一次调用,最重要的是,这不可能以插入超过 5 行的方式并行运行。例如,事务 1 和事务 2 都检查计数是否为 4(小于最大值 5),并同时进行,因此它们最终都会插入 1 行,导致总共 6 行而不是最多 5 个。
【问题讨论】:
-
dba.stackexchange.com/questions/167273/… 对你来说可能是一本有趣的书 :)
标签: sql postgresql