Postgres中的批处理条件INSERT INTO语句

时间:2019-03-19 02:48:24

标签: postgresql

我想在Postgres中使用UPSERT,但是我的版本低于9.5,所以我不能使用ON CONFILICT。我发现了这样的东西:

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

但是我该如何使用 batch 值呢? 该语句可以表达我想做的事情(它不起作用):

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

1 个答案:

答案 0 :(得分:1)

VALUES子句(CTE)中使用多个WITH,并在SELECT的{​​{1}}部分中引用它

INSERT INTO.. SELECT

DEMO