在PostgreSQL中导入期间重复键

时间:2013-03-26 18:14:27

标签: postgresql postgresql-9.1 psql

我正在关注PostgreSQL书籍,并且必须将CSV文件导入表census.lu_tracts

问题:执行INSERT查询时如下所示,我收到错误消息:

ERROR:  duplicate key value violates unique constraint "pk_lu_tracts"
DETAIL:  Key (tract_id)=(25001010800) already exists.

密钥是如何重复的? SELECT * from lu_tracs显示0行。

CREATE SCHEMA census;
set search_path=census;
CREATE TABLE lu_tracts(tract_id varchar(11), tract_long_id varchar(25)
, tract_name varchar(150)
, CONSTRAINT pk_lu_tracts PRIMARY KEY (tract_id));

INSERT INTO lu_tracts( tract_id, tract_long_id, tract_name)
SELECT geo_id2, geo_id, geo_display
FROM staging.factfinder_import
WHERE geo_id2 ~ '^[0-9]+';

1 个答案:

答案 0 :(得分:1)

正确的答案是DISTINCT ON (geo_id2),每个geo_id2只会选择一行(manual中的更多行),它应该附带一个ORDER BY子句,用于指定将选择哪一行。< / p>