【问题标题】:Insert a new value in a column and this new value should get added for other column value在列中插入一个新值,并且应该为其他列值添加这个新值
【发布时间】:2020-12-31 00:24:38
【问题描述】:

我有一个有 2 列的表格:

id   field_name
111     A
111     B
111     C
189     A
189     B
189     C

我想在我所有的 id 中添加一个新的 field_name “D”。我的表将有 6000 多个不同的 id。常规插入不起作用。

需要如下输出:

id   field_name
111     A
111     B
111     C
111     D
189     A
189     B
189     C
189     D

【问题讨论】:

    标签: sql postgresql distinct sql-insert


    【解决方案1】:

    你可以像这样使用insert ... select

    insert into mytable(id, field_name)
    select distinct id, 'D' from mytable
    

    这会为每个id 创建一行,将'D' 的常量值作为field_name

    如果你想避免已经存在的元组,如果有的话:

    insert into mytable(id, field_name)
    select distinct id, 'D' from mytable
    where not exists (select 1 from mytable t1 where t1.id = t.id and t1.field_name = 'D')
    

    或者,出于同样的目的,您可以对值的元组使用唯一索引或约束,并使用on conflict

    create unique index myidx on mytable(id, field_name);
    
    insert into mytable(id, field_name)
    select distinct id, 'D' from mytable
    on conflict (id, fieldname) do nothing;
    

    【讨论】:

    • 需要在postgres中查询。我有一个查询将获取 3036 行。我想从第 2400 行取到第 3036 行。我可以在 postgres 中限制这个吗?还是有其他想法?
    猜你喜欢
    • 1970-01-01
    • 2016-02-09
    • 2019-01-03
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    相关资源
    最近更新 更多