使用行值的Postgres UPSERT UPdate

Eri*_*c G 3 sql postgresql unique upsert

如果我的桌子是这样的

CREATE TABLE public.temperatures (
  temperature_io_id        integer NOT NULL,
  temperature_station_id   integer NOT NULL,
  temperature_value        double precision NOT NULL,
  temperature_current_kw  double precision NOT NULL,
  temperature_value_added  integer DEFAULT 1,
  temperature_kw_year_1   double precision DEFAULT 0,
  /* Keys */
  CONSTRAINT temperatures_pkey
    PRIMARY KEY (temperature_io_id, temperature_station_id, temperature_value)
) WITH (
    OIDS = FALSE
  );
Run Code Online (Sandbox Code Playgroud)

当存在io_id,station_id和温度的唯一组合时,我试图将值添加到表中。如果此组合已经存在,我想更新kw值并将1添加到value_added字段中。这将用于在该温度下保持kw的运行平均值。

INSERT INTO temperatures
(temperature_io_id, temperature_station_id, temperature_value, temperature_curr_kw)
VALUES
(20,30,40,10)
ON CONFLICT
(temperature_io_id, temperature_station_id, temperature_value)
DO UPDATE SET    
temperature_current_kwh = ((temperature_current_kw * temperature_value_added) + EXCLUDED.temperature_current_kw) / (temperature_value_added + 1),
                        temperature_value_added = temperature_value_added + 1;
Run Code Online (Sandbox Code Playgroud)

我进行更新时如何从行中访问值?尝试访问时出现模棱两可的错误temperature_current_kw

kli*_*lin 5

使用表别名:

INSERT INTO temperatures as t
    (temperature_io_id, temperature_station_id, temperature_value, temperature_current_kw)
VALUES
    (20,30,40,10)
ON CONFLICT
    (temperature_io_id, temperature_station_id, temperature_value)
DO UPDATE SET    
    temperature_current_kw = ((t.temperature_current_kw * t.temperature_value_added) + EXCLUDED.temperature_current_kw) / (t.temperature_value_added + 1),
    temperature_value_added = t.temperature_value_added + 1;
Run Code Online (Sandbox Code Playgroud)

文档所述

别名

table_name的替代名称。提供别名后,它将完全隐藏表的实际名称。当ON CONFLICT DO UPDATE指向名为excludes的表时,这特别有用,因为那也是表示要插入的行的特殊表的名称。