Postgres 行锁定

Postgres row locking

我是 Postgres 的新手(甚至 SQL)。我正在构建一个密钥数据库,它有一个名为 Key 的 table。我的问题是如何在 pg.

上执行以下操作

如果一个连接正在读取第一条记录,同时第二个连接进入,它应该读取第二条记录而不是第一条记录。 3号4号等也是一样。

您可以使用 select for update 来完成。 FOR UPDATE 导致 SELECT 语句检索的行被锁定,就好像要更新一样。这样可以防止它们被其他事务锁定、修改或删除,直到当前事务结束。

注意:

SELECT FOR UPDATE will wait for a concurrent transaction that has run any of those commands on the same row, and will then lock and return the updated row (or no row, if the row was deleted)

现在我将为您编写查询示例并说明如何操作: 假设我们有这样一个 table:

Table name: key_table

key     is_used
00001   true 
00002   true 
00003   false 
00004   false 
00005   false 

select key from key_table
where 
    is_used = false 
order by key desc
limit 1 for update
into v_key; 

update key_table
set
    is_used = true
where key = v_key;

select命令之后选定的行将被锁定。并且在更新之前,用户无法在任何其他会话中选择此行。选择此行时,所有用户都将等待此更新。在 update 命令后,用户可以显示在下一行 is_used = false