Postgres UPSERT UPdate 使用行值

Postgres UPSERT UPdate using rows values

如果我的table是这样的

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
  );

当存在 io_id、station_id 和温度的唯一组合时,我正在尝试向 table 添加值。如果这个组合已经存在,我想更新 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;

我如何在执行更新时访问行中的值?当我尝试访问 temperature_current_kw?

时出现不明确的错误

使用 table 别名:

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;

the documentation所述:

alias

A substitute name for table_name. When an alias is provided, it completely hides the actual name of the table. This is particularly useful when ON CONFLICT DO UPDATE targets a table named excluded, since that's also the name of the special table representing rows proposed for insertion.