将唯一值插入PostgreSQL

5

我在PostgreSQL中使用以下命令创建了一张表。

CREATE TABLE someTable (
    id serial primary key,
    col1 int NOT NULL,
    col2 int NOT NULL,
    unique (col1, col2)
);

然后执行2个插入语句。

  1. insert into someTable (col1,col2) values(1,11),(1,12);

    它可以正常工作。

  2. insert into someTable (col1,col2) values(1,13),(1,14),(1,11);

    出现错误(键(col1,col2)=(1,11)已存在)。

但我需要避免重复的键值对,如何实现?

我尝试了在x86_64-pc-linux-gnu上安装的PostgreSQL 9.5.0和PostgreSQL 9.3 ,但都出现了错误。

我需要在执行两个语句后添加如下内容。

(1,11),(1,12),(1,13),(1,14)

第二个插入语句试图插入已经在第一个语句中插入的值(1,11)。由于您已经将col1,col2定义为唯一,因此无法两次插入相同的元组。 - user330315
能否插入所有其他值(避免重复对)? - Abdul Manaf
不能用Postgres 9.1做到,你需要使用Postgres 9.5。 - user330315
请参见以下链接以获取与旧版本Postgres的可能解决方案:https://dev59.com/onNA5IYBdhLWcg3wVcFx 和 https://dev59.com/uHNA5IYBdhLWcg3wC5Xh。需要注意的是,9.1版本即将在8个月内停止支持,因此您应该计划进行升级。 - user330315
显示剩余5条评论
2个回答

4
您可以使用insert . . . select来完成此操作:
insert into someTable(col1, col2) 
    select col1, col2
    from (select 1 as col1, 13 as col2 union all
          select 1, 14 union all
          select 1, 11
         ) t
    where not exists (select 1
                      from someTable st
                      where st.col1 = t.col1 and st.col2 = t.col2
                     );

也就是说,在insert之前要过滤掉这些值。
编辑:
正如a-horse-with-no-name指出的那样,您也可以将其编写为:
insert into someTable(col1, col2) 
    select col1, col2
    from (values (1, 13), (1, 14), (1, 11)
         ) as t(col1, col2)
    where not exists (select 1
                      from someTable st
                      where st.col1 = t.col1 and st.col2 = t.col2
                     );

我倾向于使用union all方法,因为并非所有数据库都支持使用values()语句的方式。


1
在派生表中不需要冗长的 select。你可以直接使用 values (1,13), (1,14) - user330315
我从上面的语法中得到了错误信息 ERROR: "from" 附近有语法错误 第二行: from (values (1, 13), (1, 14), (1, 11) - Abdul Manaf
@AbdulManaf……在from前面不知道为什么少了select - Gordon Linoff

3
使用最新发布的PostgreSQL 9.5版本。
使用以下查询语句:
insert into someTable (col1,col2) values(1,13),(1,14),(1,11) ON CONFLICT DO NOTHING;

这将避免重复代码而不需要任何额外的代码行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接