简体   繁体   中英

Batch Conditional INSERT INTO statement in Postgres

I want to UPSERT in Postgres, but my version is below 9.5 so I cannot use ON CONFILICT . I found something like this:

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

But how can I do this with batch values? This statement might can express what I want to do (It cannot work):

INSERT INTO result_data (HOST_ID, RESOURCE_TYPE, TIMESTAMP, UPPER, LOWER, AVG) 
    (values ("xxxxx", "cpu", 1544313900, 80, 70, 75), ("aaaaaa", "cpu", 1544314000, 80, 70, 75))
    AS result2(HOST_ID, RESOURCE_TYPE, TIMESTAMP, UPPER, LOWER, AVG) 
    WHERE NOT EXISTS(SELECT 1 FROM result_data WHERE result2.HOST_ID = result_data.HOST_ID);

Use multiple VALUES in a WITH clause ( CTE ) and refer to it in the SELECT part of a INSERT INTO.. SELECT

with result2(HOST_ID, RESOURCE_TYPE, TIMESTAMP, UPPER, LOWER, AVG)  AS
(
 VALUES  ('xxxxx', 'cpu', 1544313900,  80, 70, 75 ), 
         ('aaaaaa', 'cpu', 1544314000, 80, 70, 75 ) 
)
 SELECT * FROM   result2 r2 
   WHERE  NOT EXISTS 
           ( 
             SELECT 1 
               FROM   result_data r 
              WHERE   r.host_id = r2.host_id )

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM