如何将块中的转换数据插入到原始 table 中?

How to insert transformed data in a block back into original table?

我很确定以前有人会问这个问题,但我找不到答案,因为我不知道应该搜索什么术语。

我有一个 table:

create table tmp_test (
    id serial primary key,
    value integer,
    value_2 numeric
);

最初我们可能会在 table 中找到以下条目:

id    value    value_2
______________________
1     4        NULL 
2     3        NULL
3     5        NULL
...

我已经提取了前两列,并进行了转换以获得第三列,现在我想更新tmp_table,使其看起来像这样:

id    value    value_2
______________________
1     4        5.2
2     3        1.3
3     5        2.1
...

有没有办法一次完成所有操作,而不是循环遍历行并执行如下语句:

update tmp_table set value_2 = 5.2 where id = 1 and value = 4;

只需这样做:

update tmp_table set value_2 = value_1 / 2.0;

这将立即更新所有行(因为没有 where 子句)。另请注意,在 value_2 赋值的右侧,我们可以引用其他列(在本例中为 value_1 列)。

我假设您想将在您的应用程序中计算的一组数字插入列 value_2。 使用两个数组,一个用于 ids,另一个用于 values:

select
    unnest(array[1, 2, 3]) id,
    unnest(array[5.2, 1.3, 2.1]) as value

 id | value 
----+-------
  1 |   5.2
  2 |   1.3
  3 |   2.1
(3 rows)

使用主键识别值并使用上述查询更新 table:

update tmp_test t
set value_2 = n.val
from (
    select
        unnest(array[1, 2, 3]) id,
        unnest(array[5.2, 1.3, 2.1]) as val
    ) n
where t.id = n.id;
select * from tmp_test;

 id | value | value_2 
----+-------+---------
  1 |     4 |     5.2
  2 |     3 |     1.3
  3 |     5 |     2.1
(3 rows)