向 postgresql 插入唯一值
insert unique values to postgresql
我在 postgresql 中使用以下命令创建一个 table。
CREATE TABLE someTable (
id serial primary key,
col1 int NOT NULL,
col2 int NOT NULL,
unique (col1, col2)
);
然后执行 2 条插入语句。
insert into someTable (col1,col2) values(1,11),(1,12);
有效
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 (Ubuntu 4.8.2-19ubuntu1) 4.8.2、64 位和 x86_64-pc-linux-gnu 上的 PostgreSQL 9.3 编译,由gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2,64 位
但是我得到了错误
执行两条语句后,我需要这样放。
(1,11),(1,12),(1,13),(1,14)
您可以使用 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()
语句。
使用 postgresql 9.5(最新版本)
像这样使用查询
insert into someTable (col1,col2) values(1,13),(1,14),(1,11) ON CONFLICT DO NOTHING;
它将避免重复,无需任何额外的代码行。
我在 postgresql 中使用以下命令创建一个 table。
CREATE TABLE someTable (
id serial primary key,
col1 int NOT NULL,
col2 int NOT NULL,
unique (col1, col2)
);
然后执行 2 条插入语句。
insert into someTable (col1,col2) values(1,11),(1,12);
有效
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 (Ubuntu 4.8.2-19ubuntu1) 4.8.2、64 位和 x86_64-pc-linux-gnu 上的 PostgreSQL 9.3 编译,由gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2,64 位
但是我得到了错误
执行两条语句后,我需要这样放。
(1,11),(1,12),(1,13),(1,14)
您可以使用 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()
语句。
使用 postgresql 9.5(最新版本)
像这样使用查询
insert into someTable (col1,col2) values(1,13),(1,14),(1,11) ON CONFLICT DO NOTHING;
它将避免重复,无需任何额外的代码行。