Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres UPSERT UPdate using rows values

If my table looks like this

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

I'm trying to add values to the table when there is a unique combination of io_id, station_id and temperature. If this combination already exists, i want to update the kw value and add 1 to the value_added field. This will be used to keep a running average of the kw at the temperature.

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;

How can i access the values from the row when im doing the update? I get an ambiguous error when i try to access temperature_current_kw?

like image 406
Eric G Avatar asked Oct 27 '25 04:10

Eric G


1 Answers

Use a table alias:

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;

As stated in 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.

like image 62
klin Avatar answered Oct 29 '25 17:10

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!