簡體   English   中英

PostgreSQL開沖突

[英]PostgreSQL ON CONFLICT ON

我的查詢有問題,因為它似乎模棱兩可。 我需要在表中插入新行,但是如果我插入編號相同的項目,則只能更新數量。

cur.execute(
  """INSERT INTO store VALUES(DEFAULT, %s, %s, %s, %s, %s, %s, %s)
                ON CONFLICT (number) 
                DO UPDATE SET quantity=quantity+%s""", 
  (
    name, producent, model, number, quantity, 
    warehouse, location, quantity
  )
)

您嘗試解決的一般問題是名稱“merge”或“upsert” ,因為您希望“更新現有行,但如果原始操作中沒有現有行則插入新行”。 你正確使用PostgreSQL的INSERT … ON CONFLICT (…) DO UPDATE …來解決這個問題。

您的特定問題是在更新的情況下如何基於現有字段值設置字段值。 ON CONFLICT子句的PostgreSQL文檔解決了這個問題:

ON CONFLICT DO UPDATESETWHERE子句可以使用表的名稱(或別名)訪問現有行,並使用特殊excluded表訪問建議插入的行。

因此,您的SET子句可以處理excluded表以獲取建議的quantity值:

INSERT INTO store
VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (number) DO
UPDATE SET quantity = (store.quantity + excluded.quantity)

bignose的答案包含了解決方案的線索:由於quantityexcluded表和原始表的一列,因此您必須消除歧義:

... DO UPDATE SET quantity = store.quantity + %s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM