仅当值不存在时才从SELECT插入表

时间:2015-12-17 16:19:15

标签: sql postgresql sql-insert upsert

我希望table1.id仅在table2.t1col中不存在table1.id的情况下插入table2.t1col

我想我必须使用:

insert into table2 name (t1col) value (select id from table1)

但我想仅在id中不存在table2时添加。

5 个答案:

答案 0 :(得分:2)

唯一/索引约束保证了值的唯一性。因此,建议使用。

不幸的是,违反约束会导致整个insert失败。所以,你可以这样做:

insert into table2(t1col) 
    select id
    from table1 t1
    where not exists (select 1 from table2 t2 where t2.t1col = t1.id);

您还应该有一个唯一的索引/约束来防止将来出现问题。

答案 1 :(得分:1)

您可以使用唯一索引来防止重复的行。

但是如果你想插入过滤它的行来不插入重复的行,你可以这样做。

INSERT INTO table2 (idcol)
SELECT id FROM table1
EXCEPT
SELECT idcol FROM table2;

答案 2 :(得分:1)

如果您UNIQUE上有PRIMARY KEYtable2.t1col约束,就像您最有可能的那样, Postgres 9.5 (目前有更优雅的解决方案)测试版,现在很快发布)。使用新的UPSERT实施INSERT ... ON CONFLICT DO NOTINGQuoting the manual:

  

可选的ON CONFLICT子句指定了替代操作   提出唯一违规或排除约束违规错误。   对于建议插入的每个单独行,要么插入   收益,或者,如果由仲裁者约束或指数指定   违反了conflict_target,采取了替代性的conflict_action。    ON CONFLICT DO NOTHING只是避免插入行作为替代操作。

大胆强调我的。

所以你可以简单地说:

INSERT INTO table2(t1col)
SELECT id FROM table1
ON CONFLICT DO NOTHING;

如果table1.id未定义为唯一,使唯一:

INSERT INTO table2(t1col)
SELECT DISTINCT id FROM table1
ON CONFLICT DO NOTHING;

对于Postgres 9.4 ,您可以在此处找到技术概述:

答案 3 :(得分:0)

在该列上创建一个唯一索引并完成它。无需检查。

class extends React.Component

http://www.postgresql.org/docs/9.4/static/indexes-unique.html

答案 4 :(得分:-1)

使用此查询

INSERT INTO table2 name (t1col) value 
(
    SELECT t1.id FROM table1 t1, table2 t2
    WHERE t1.id <> t2.id
)
相关问题