首页 > 解决方案 > 插入现有表时自动更新主键?

问题描述

实际上,我的问题与此处基本相同,但我需要将嵌套查询中的值插入现有表中,而且我对 sql 并不熟悉,不知道如何将setval部分合并到我的查询中:

insert into table_a
select * 
from table_b 
where val_1 IN (select "val_1" from table_c where "val_2" is null)

返回

ERROR:  duplicate key value violates unique constraint "table_a_pkey"
DETAIL: Key (qid)=(470971) already exists.

现在我知道我可以按照此处所述使用 drop column 和 autgenerate 解决方法,但必须有一种更优雅的方式。我正在使用 Postgresql/Postgis 2.4 顺便说一句。

标签: postgresqlprimary-keysql-insert

解决方案


如果主键是自动生成的,请不要插入 PK 列:

insert into table_a (some_column, other_column, third_column)
select some_column, other_column, third_column
from table_b 
where val_1 IN (select "val_1" from table_c where "val_2" is null)

(我不得不猜测列名,因为您没有提供真实的列名)


推荐阅读