我的查询有问题,因为它似乎不明确。我需要的是在我的表格中插入新的行,但是如果我插入的项目具有相同的编号,它应该只更新数量。
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
)
)发布于 2019-03-15 07:06:48
您试图解决的一般问题的名称是“merge” or “upsert”,因为您希望在原子操作中“更新现有行,但如果没有现有行,则插入新行”。您使用PostgreSQL's INSERT … ON CONFLICT (…) DO UPDATE …来解决这个问题是正确的。
您的具体问题是,在更新的情况下,如何根据现有的字段值设置字段值。ON CONFLICT子句的PostgreSQL文档解决了这个问题:
ON CONFLICT DO UPDATE中的SET和WHERE子句可以使用表名(或别名)访问现有行,也可以使用特殊的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)发布于 2019-03-15 15:09:05
excluded的答案包含了解决方案的线索:由于quantity是一个包含excluded和原始表的列,因此您必须消除歧义:
... DO UPDATE SET quantity = store.quantity + %shttps://stackoverflow.com/questions/55171917
复制相似问题