【问题标题】:Update each row with a new entity用新实体更新每一行
【发布时间】:2020-09-07 10:04:55
【问题描述】:

我有两张桌子:

CREATE TABLE public.test
(
    id integer NOT NULL GENERATED ALWAYS AS IDENTITY
)

CREATE TABLE public.test2
(
    id integer,
    test_id integer
)

test2 有两行(1,null)和(2,null)。表test 什么都没有。现在我想通过在test 中创建新行来填充 test_id。我每次都需要一个新实体,以便拥有 (1, 1)、(2, 2) 等。我尝试使用 insert 语句准备 update 查询,但我不明白该怎么做.这是我尝试的:

update t2 set t2.test_id = t.id
from test2 t2 full join (INSERT INTO test(id) VALUES (default) RETURNING id) t on t2.test_id = t.id

但我得到以下信息:

ERROR:  syntax error at or near "INTO"
LINE 2: from test2 t2 full join (INSERT INTO test(id) VALUES (defaul...
                                        ^
SQL state: 42601
Character: 65

我能以某种方式创建我想要的查询吗?

【问题讨论】:

  • test 中真的只有一列,还是还有其他列?
  • 这只是为了测试

标签: sql postgresql sql-update sql-insert bulkupdate


【解决方案1】:

目标表中只有一列会使事情变得有些棘手。首先使用next_val,然后使用insert test 中的值(我们需要将选项overriding system value 插入到generated always 列中)来生成和分配新ID 可能会更简单,)

with t2 as (
    update test2
    set test_id = nextval('test_id_seq')
    where test_id is null
    returning test_id
) 
insert into test(id) overriding system value 
select test_id from t2

Demo on DB Fiddlde

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多