sql - 仅当值不存在时才从 SELECT 插入到表中

标签 sql postgresql sql-insert upsert

只有当 table2 中不存在 table1.id 时,我才想将 table1.id 插入到 table2.t1col 中。 t1col,然而。

我想我必须使用:

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

但我只想在 table2 中不存在 id 的情况下添加。

最佳答案

唯一/索引约束保证值的唯一性。所以,推荐。

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

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

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

关于sql - 仅当值不存在时才从 SELECT 插入到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34339403/

相关文章:

django - 如何在 Django F 表达式中将日期和时间字段合并为日期时间字段

java - postgres : inserting array of custom type

sql - PostgreSQL - 选择一列和两列中唯一值的计数

php - 如何将表的行从一个数据库插入到另一个数据库(使用两个 PDO)

sql - "INSERT INTO tab SELECT * FROM another_tab"的 UPSERT

php - 无法使用 php pred-statement 将记录插入 mysql 表

mysql - 如何在mysql中检索重复的记录

sql - 在 MS Access 中转置和聚合 SQL 查询

sql - Flyway 在命名约定中自定义 'version'

sql - 在 SQL Server 2008R2 中创建链接服务器时出错