【问题标题】:Update only the greatest row - Sequential Based Update仅更新最大的行 - 基于顺序的更新
【发布时间】:2022-01-08 21:25:05
【问题描述】:

我想编写一个查询来查找 status = REQUEST_PENDING 的 LOWEST SEQUENCE,然后在某个条件后更新它。

例如:

person_name status sequence
a request_progressed 1
b request_pending 2
c request_pending 3

如果名为 A 的人已经完成,它的状态将从“request_progressed”变为“request_done”;然后下一个 B 的状态将更改为“request_progressed”,而 C 保持不变,因为它的顺序是第 3 个。

所以我只需要知道如何通过找到具有“request_pending”状态的最低序列并且表上只有一个“request_progressed”来更改 B 人的状态,这就是为什么当它是更新为“request_done”,下一个“request_pending”需要更新为“request_progressed”。

我尝试了以下方法:

update table
set status = 'request_progressed'
where status = 'pending' AND sequence = min(sequence)

【问题讨论】:

  • 这将真正受益于适当的样本数据和预期结果,请参阅Minimal, Reproducible Example
  • 首先如何对数据进行排序?是什么决定了 b 是否出现在 c 之前而不是相反?
  • 查询不能。触发器也不能。该任务可以以存储过程格式解决。
  • 我想写一个查询来找到LOWEST SEQUENCE AND REQUEST_PENDING STATUS,然后在某个条件后更新它。这是否意味着(1)column_status可能有一个3 个值 - 'request_pending', 'request_progressed', 'request_done'; (2) 在任何时候,表中只有一行(不多也不是没有)可能有值'request_progressed'
  • @Akina 是的,只有一个 request_progressed,我会编辑它

标签: mysql sql postgresql sql-update


【解决方案1】:

在 MySQL 中 - 您可以在更新查询中指定 order by 和 limit:

update t
set status = 'request_progressed'
where status = 'request_pending'
order by sequence
limit 1

在 PostgreSQL 中 - 你仍然需要 order by 和 limit 但它们只能在子查询中使用:

update t
set status = 'request_progressed'
where (status, sequence) in (
    select status, sequence
    from t
    where status = 'request_pending'
    order by sequence
    offset 0 rows fetch first 1 row only
)

【讨论】:

  • 您好,感谢您的回答。但是,它会给出这样的错误 -> SQL 错误 [42601]: ERROR: syntax error at or near "order"
  • 这是mysql还是别的什么?
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2017-03-07
  • 2020-07-21
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多