将唯一值插入postgresql

Abd*_*naf 5 sql sql-insert postgresql-9.3

我在postgresql中使用下面的命令创建一个表.

CREATE TABLE someTable (
    id serial primary key,
    col1 int NOT NULL,
    col2 int NOT NULL,
    unique (col1, col2)
);
Run Code Online (Sandbox Code Playgroud)

然后我执行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);

    得到错误(key(col1,col2)=(1,11)已经存在.

但我需要避免重复对.怎么可能?

我试试这个

x86_64-pc-linux-gnu上的PostgreSQL 9.5.0,由gcc编译的gcc(Ubuntu 4.8.2-19ubuntu1)4.8.2,64位和PostgreSQL 9.3,由gcc编译(Ubuntu 4.8. 2-19ubuntu1)4.8.2,64位

但我得到了错误

执行两个语句后我需要这样做.

(1,11),(1,12),(1,13),(1,14)
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 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
                     );
Run Code Online (Sandbox Code Playgroud)

也就是说,过滤掉 之前的值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
                     );
Run Code Online (Sandbox Code Playgroud)

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