Postgres 9.2 INSERT 从具有分隔值的字符串中跳过重复项

Postgres 9.2 INSERT skipping duplicates from string with separated values

Postgres 版本 9.2

如何将数据插入 table(table 有单列 "name")非重复值,只需一个查询。 重复插入时没有 Postgres 错误。

例如 table 有两行的值为:

AAA, BBB

我有数据字符串逗号分隔值:

'AAA,BBB,CCC'

我想创建 INSERT 查询,之后 table 中的执行数据将是树行:

AAA, BBB, CCC

Postgres 9.5 有很好的 INSERT 参数 "ON CONFLICT DO NOTHING",但我的 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);