【问题标题】:How to update table with field Postgres如何使用字段 Postgres 更新表
【发布时间】:2021-02-11 00:30:56
【问题描述】:

我有这样的表:

Incident_id 是外键。我想要实现它-> 再创建一个具有命名位置(int)的列。并像这样填充它:查找每个 event_id 的所有行,并使用每个 event_id 获得的索引或行列表更新每一行。例子: event_id 5 与 4 个注释行匹配,因此该位置的更新将相应地为 0、1、2、3。类型

【问题讨论】:

    标签: sql postgresql sql-update window-functions sql-view


    【解决方案1】:

    我不建议存储此类派生信息。相反,您可以创建一个使用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
    

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


    编辑

    如果您真的想在新列中实现该值,并考虑到表的主键,您可以这样做:

    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;
    

    【讨论】:

    • 迁移一次。我需要将其填充到 column.ty
    • @Demitriush:你的表的主键是什么?
    • incident_note_id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多