从 PostgreSQL 表中 POP 一行

Dan*_*ner 2 postgresql

什么相当于PostgresSQL 中的 Redis LPOP命令?

例如,在下表中,以包含两行 a 和 bthings的单列命名thing

thing
----
a
b
Run Code Online (Sandbox Code Playgroud)

What's a correct command to atomically remove and return a row in the table? Using the above example, I'd expect it to return a single row ('a') and delete it as part of a transaction/lock.

a_h*_*ame 5

您可以使用数据修改公用表表达式来做到这一点:

with deleted as (
  delete from things
  where thing = 'a'
  returning *
)
select *
from deleted;
Run Code Online (Sandbox Code Playgroud)

  • @DanTanner:是的,每个 SQL 语句都是原子执行的。您是否知道没有默认的“顺序”或行?所以你的语句可能会返回一个随机行,而不是带有“a”的行 (2认同)