将唯一值插入postgresql
发布时间:2020-12-13 16:02:41 所属栏目:百科 来源:网络整理
导读:我在 postgresql中使用下面的命令创建一个表. CREATE TABLE someTable ( id serial primary key,col1 int NOT NULL,col2 int NOT NULL,unique (col1,col2)); 然后我执行2个插入语句. 插入someTable(col1,col2)值(1,11),(1,12); 它的工作 插入someTable(col1,
我在
postgresql中使用下面的命令创建一个表.
CREATE TABLE someTable ( id serial primary key,col1 int NOT NULL,col2 int NOT NULL,unique (col1,col2) ); 然后我执行2个插入语句. >插入someTable(col1,col2)值(1,11),(1,12); 它的工作 得到错误(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,12),14) 解决方法
您可以使用insert执行此操作. . .选择:
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 into someTable(col1,col2 from (values (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()语句. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |