使用行值Postgres UPSERT UPdate

时间:2016-01-28 21:02:56

标签: 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
  );

当io_id,station_id和temperature的唯一组合时,我正在尝试向表中添加值。如果此组合已存在,我想更新kw值并将value1添加到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时,我收到了一个含糊不清的错误?

1 个答案:

答案 0 :(得分:4)

使用表别名:

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中所述:

  

别名

     

table_name的替代名称。提供别名时,它会完全隐藏表的实际名称。这是特别的   在ON CONFLICT DO UPDATE定位一个名为excluded的表时很有用,   因为那也是表示行的特殊表的名称   建议插入。