在列中插入一个新值,并且应该为其他列值添加这个新值
Insert a new value in a column and this new value should get added for other column value
我有一个包含 2 列的 table:
id field_name
111 A
111 B
111 C
189 A
189 B
189 C
我想为我所有的 ID 添加一个新的 field_name“D”。我的 table 将有 6000 多个不同的 ID。常规插入不起作用。
需要如下输出:
id field_name
111 A
111 B
111 C
111 D
189 A
189 B
189 C
189 D
您可以像这样使用 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;
我有一个包含 2 列的 table:
id field_name
111 A
111 B
111 C
189 A
189 B
189 C
我想为我所有的 ID 添加一个新的 field_name“D”。我的 table 将有 6000 多个不同的 ID。常规插入不起作用。
需要如下输出:
id field_name
111 A
111 B
111 C
111 D
189 A
189 B
189 C
189 D
您可以像这样使用 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;