简体   繁体   English

如何在 PostgreSQL 中更新或插入

[英]How to UPDATE or INSERT in PostgreSQL

I want to UPDATE or INSERT a column in PostgreSQL instead of doing INSERT or UPDATE using INSERT ... ON CONFLICT ... because there will be more updates than more inserts and also I have an auto incrementing id column that's defined using SERIAL so it increments the id column everytime it tries to INSERT or UPDATE and that's not what I want, I want the id column to increase only if it's an INSERT so that all ids would be in an order instead我想在PostgreSQL UPDATE or INSERT一列,而不是使用INSERT ... ON CONFLICT ...进行INSERT or UPDATE INSERT ... ON CONFLICT ...因为会有更多的更新而不是更多的插入,而且我有一个使用SERIAL定义的自动递增 id 列,所以它每次尝试插入或更新时都会增加 id 列,这不是我想要的,我希望 id 列仅在插入时增加,以便所有 id 都按顺序排列

The table is created like this该表是这样创建的

CREATE TABLE IF NOT EXISTS table_name (
    id SERIAL PRIMARY KEY,

    user_id varchar(30) NOT NULL,
    item_name varchar(50) NOT NULL,
    code_uses bigint NOT NULL,

    UNIQUE(user_id, item_name)
)

And the query I used was我使用的查询是

INSERT INTO table_name
VALUES (DEFAULT, 'some_random_id', 'some_random_name', 1)
ON CONFLICT (user_id, item_name)
DO UPDATE SET code_uses = table_name.code_uses + 1;

Thanks :)谢谢 :)

Upserts in PostgreSQL do exactly what you described. PostgreSQL 中的Upserts完全符合您的描述。

Consider this table and records考虑这个表和记录

CREATE TABLE t (id SERIAL PRIMARY KEY, txt TEXT);
INSERT INTO t (txt) VALUES ('foo'),('bar');

SELECT * FROM t ORDER BY id;

 id | txt 
----+-----
  1 | foo
  2 | bar
(2 Zeilen)

Using upserts the id will only increment if a new record is inserted使用 upserts id 只会在插入新记录时增加

INSERT INTO t VALUES (1,'foo updated'),(3,'new record')
ON CONFLICT (id) DO UPDATE SET txt = EXCLUDED.txt;

SELECT * FROM t ORDER BY id;

 id |     txt     
----+-------------
  1 | foo updated
  2 | bar
  3 | new record
(3 Zeilen)

EDIT (see coments): this is the expected behaviour of a serial column, since they're nothing but a fancy way to usesequences .编辑(见评论):这是serial列的预期行为,因为它们只是一种使用sequences的奇特方式。 Long story short: using upserts the gaps will be inevitable .长话短说:使用 upserts the gaps will be inevitable If you're worried the value might become too big, use bigserial instead and let PostgreSQL do its job.如果您担心该值可能会变得太大,请改用bigserial并让 PostgreSQL 完成它的工作。

Related thread: serial in postgres is being increased even though I added on conflict do nothing相关主题: postgres 中的串行正在增加,即使我添加了冲突什么都不做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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