如何使用字段 Postgres 更新 table

How to update table with field Postgres

我有 table 这样的:

Incident_id 是外键。我想要实现的目标 -> 再创建一个名为 position (int) 的列。并像这样填充它:找到每个 incident_id 的所有行,并用每个 incident_id 得到的索引或行列表更新每一行。例子: incident_id 5 个匹配项有 4 个注释行,因此更新的位置将相应地为 0、1、2、3。泰

我不建议存储此类派生信息。相反,您可以创建一个视图,该视图使用 row_number() 枚举每个 incident_id:

的行
create view myview as
select t.*, row_number() over(partition by incident_id order by id) - 1 rn
from mytable t

要获得 stable 结果,您需要一个可用于对每个事件的行进行一致排序的列:我在查询中将其称为 id。您可以将其更改为您的用例的相关列名(或列集);您通常会使用 table.

的主键列

编辑

如果您真的想在新列中具体化该值,并考虑到 table 的主键,您可以这样做:

alter table mytable add column position int;

update mytable t
set position = t1.position
from (
    select incident_note_id, 
        row_number() over(partition by incident_id order by incident_note_id) - 1 position
    from mytable
) t1
where t1.incident_note_id = t.incident_note_id;