Postgres version 9.2
如何将数据插入表(表具有单列"名称"(非重复值,只需一个查询。重复插入时没有Postgres错误。
例如,表有两行带有值:
AAA, BBB
我有数据字符串逗号分隔的值:
'AAA,BBB,CCC'
我想创建 INSERT 查询,之后表中的执行数据将是树行:
AAA, BBB, CCC
Postgres 9.5 有很好的插入参数"冲突时什么都不做",但我的 postgres 版本不支持它。
你可以尝试NOT EXISTS
构造:
db=# create table t(i int primary key);
CREATE TABLE
db=# with d(v) as (values(1),(2),(3))
insert into t select v from d;
INSERT 0 3
db=# with d(v) as (values(1),(2),(3),(4))
insert into t select v from d where not exists (select 1 from t where i =v);
INSERT 0 1
或者使用 PLPGSQL 和exception
处理(用于原子性(
找到具有单个查询的解决方案:
INSERT INTO table (name)
SELECT * FROM unnest(string_to_array('AAA,BBB,CCC', ',')) col
WHERE col NOT IN (SELECT name FROM table);