【问题标题】:Postgres insert multiple rows if does not exist, return all id's if exists or inserted, then use all ids to insert into another tablePostgres 如果不存在则插入多行,如果存在或插入则返回所有 id,然后使用所有 id 插入另一个表
【发布时间】:2021-10-03 16:42:38
【问题描述】:

我在节点服务器中有一个字符串数组。我想将每个字符串作为标签插入到 table1 中。每个标签行都有tag_id和tag_text,其中tag_id是一个序列值,tag_text是对应的字符串。

如果这些标签尚不存在,我想插入它们,并返回所有标签的 id,无论每个标签是否已插入或已存在。是否可以在单个查询中执行此操作?

此外,我想使用上面查询中返回的 id 并将每个 id 连同一个常量值(在节点服务器中定义)插入另一个表(table2)中。是否有可能在一次交易中完成所有这些工作?如果有,怎么做?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    你可以使用returning子句:

    insert into table1 (tag)
        select tag
        from unnest($tag_array) tag
        on conflict (tag)
        do update set tag = excluded.tag
        returning (*);
    

    这应该返回所有标签,无论它们是否在表格中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 2013-06-18
      • 2019-09-06
      • 1970-01-01
      • 2013-08-14
      • 2014-04-28
      • 2011-05-03
      相关资源
      最近更新 更多