[英]How to UPDATE or INSERT in PostgreSQL
我想在PostgreSQL
UPDATE or INSERT
一列,而不是使用INSERT ... ON CONFLICT ...
進行INSERT or UPDATE
INSERT ... ON CONFLICT ...
因為會有更多的更新而不是更多的插入,而且我有一個使用SERIAL
定義的自動遞增 id 列,所以它每次嘗試插入或更新時都會增加 id 列,這不是我想要的,我希望 id 列僅在插入時增加,以便所有 id 都按順序排列
該表是這樣創建的
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)
)
我使用的查詢是
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;
謝謝 :)
PostgreSQL 中的Upserts
完全符合您的描述。
考慮這個表和記錄
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)
使用 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)
編輯(見評論):這是serial
列的預期行為,因為它們只是一種使用sequences
的奇特方式。 長話短說:使用 upserts the gaps will be inevitable
。 如果您擔心該值可能會變得太大,請改用bigserial
並讓 PostgreSQL 完成它的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.