错误:无法创建唯一索引PSQL

时间:2015-03-26 15:34:12

标签: sql database postgresql

我目前正在处理我的psql我的第一个psql数据库,如下所示:

DROP TABLE IF EXISTS test_table_a;
DROP TABLE IF EXISTS test_table_b;

CREATE TABLE test_table_a (
    test_name_a varchar (150) NOT NULL,
    test_num_a integer NOT NULL
);
ALTER TABLE test_table_a OWNER TO me;

CREATE TABLE test_table_b (
    test_name_b varchar (150) NOT NULL,
    test_num_b integer NOT NULL
);
ALTER TABLE test_table_b OWNER TO me;

CREATE TABLE test_table_c (
    test_name_a varchar (150) NOT NULL,
    test_num_a integer  NOT NULL,
    test_num_b integer NOT NULL,
    test_name_b varchar(150) NOT NULL,

);
ALTER TABLE test_table_c OWNER TO me;

然后我用数据加载它......:

echo COPY test_table_a FROM location_x
psql -c "COPY (
    SELECT DISTINCT
        test_num_a,
        test_name_a,
    FROM location_x
  ) TO STDOUT;" location_x | \
  psql -c "COPY test_table_a FROM STDIN;" me

echo COPY test_table_b FROM location_x
psql -c "COPY (
    SELECT DISTINCT
        test_num_b,
        test_name_b,
    FROM location_x
  ) TO STDOUT;" location_x | \
  psql -c "COPY test_table_b FROM STDIN;" me


echo COPY test_table_c FROM location_x
psql -c "COPY (
    SELECT DISTINCT
        test_num_a,
        test_name_a,
        test_num_b,
        test_name_b
    FROM location_x
  ) TO STDOUT;" location_x | \
  psql -c "COPY test_table_c FROM STDIN;" me

然后我尝试添加密钥,这是在我生成以下错误时:

ERROR: could not create unique index "pk_test_num_a" DETAIL: KEY (test_num_a) = (128) is duplicated. ERROR: could not create unique index "pk_test_num_b" DETAIL: KEY (test_num_b) = (110) is duplicated.

当我跑步时:

ALTER TABLE divDemographic
    ADD CONSTRAINT pk_test_num_b PRIMARY KEY (test_num_b);

ALTER TABLE schDemographic
    ADD CONSTRAINT pk_test_num_a PRIMARY KEY (test_num_a);

ALTER TABLE test_table_c
    ADD CONSTRAINT fk_test_num_a FOREIGN KEY (test_num_a) REFERENCES test_table_a(test_num_a),
    ADD CONSTRAINT fk_test_num_b FOREIGN KEY (test_num_b) REFERENCES test_table_b(test_num_b);

我认为使用"复制" select语句中的说明符会阻止这个,有关如何修复此错误的任何想法?谢谢

1 个答案:

答案 0 :(得分:2)

SELECT DISTINCT通过比较所有选定的列来检测重复的行:显然,您有 test_num_a = 128的行和不同的 test_name_a ,这些行是不同的。

源表 location_x 的内容有缺陷,或者您实际上无法将 test_num_a 用作主键。