我如何插入很多,如果它已经存在,不要对 PG-promise 做任何事情
how do I insert many, if it already exists, dont do anything with PG-promise
错误:duplicate key value violates unique constraint "users_pkey"
我正在使用 Node 和 PG-Promise
我正在向我的数据库中批量插入大量数据。有时,数据已经存在,所以我需要覆盖它或忽略该行。
我看到我可以做到这一点:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
但是当我批量插入时,我似乎无法弄清楚如何使用 PG-Promise 做到这一点。
let users = [...]
const query = pgp.helpers.insert(users, userTable)
语法是什么样的?
根据https://github.com/vitaly-t/pg-promise/issues/542,
simply append the ON CONFLICT
part to your query, and that's it.
所以在你的情况下
const users = […];
const query = pgp.helpers.insert(users, cs) + ' ON DUPLICATE KEY UPDATE';
其中cs
是你的ColumnSet object. You also will typically use assignColumns方法,从同一个link可以看出。
请注意 proper Postgres INSERT
syntax 使用 ON CONFLICT DO UPDATE …
。
错误:duplicate key value violates unique constraint "users_pkey"
我正在使用 Node 和 PG-Promise
我正在向我的数据库中批量插入大量数据。有时,数据已经存在,所以我需要覆盖它或忽略该行。
我看到我可以做到这一点:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
但是当我批量插入时,我似乎无法弄清楚如何使用 PG-Promise 做到这一点。
let users = [...]
const query = pgp.helpers.insert(users, userTable)
语法是什么样的?
根据https://github.com/vitaly-t/pg-promise/issues/542,
simply append the
ON CONFLICT
part to your query, and that's it.
所以在你的情况下
const users = […];
const query = pgp.helpers.insert(users, cs) + ' ON DUPLICATE KEY UPDATE';
其中cs
是你的ColumnSet object. You also will typically use assignColumns方法,从同一个link可以看出。
请注意 proper Postgres INSERT
syntax 使用 ON CONFLICT DO UPDATE …
。