postgres upsert 查询

时间:2021-07-07 04:37:59

标签: postgresql

我正在尝试将 UPSERT 命令用于使用 Java 的 postgress sql DB 版本 > 9.5 并看到这篇文章: http://flyingjxswithjava.blogspot.com/2016/12/sql-upsert-syntax-and-examples.html

它概述了两种方法:

  • 使用 ON CONFLICT 子句:
INSERT INTO store (id, name) values (559, 'Unforgettable Fruits')
ON CONFLICT (id)
DO UPDATE SET name = 'Unforgettable Fruits';

  • 使用 WITH 子句:语法:

WITH upsert AS
          (UPDATE <table name>
                SET <column name> = <value>
                WHERE <condition> RETURNING *)
          INSERT into <table name> (<columns separated by comma>)
                SELECT <values separated by comma>
                WHERE not exists (SELECT * from upsert);

我的问题是:推荐使用哪种方法以及使用哪种方法有效。

0 个答案:

没有答案