sql—将数据从一列插入/更新到另一列,并在更新时发生冲突,是否仅对特定字段具有不同值的数据?

2uluyalo  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(273)

我有两列 products/tmp_products 具有以下规格 (id bigint primary key ,price int not null,quantity int not null ,lastupdate timestamp) 我想让sql
                  当id不在产品中时,从tmp\U产品插入产品。
                  仅在(价格或数量)值更改时更新。

INSERT INTO products(id,price,quantity,lastupdate)
            SELECT  (id,price,quantity,lastupdate) FROM tmp_products
    ON CONFLICT (id) DO UPDATE SET
    price=EXCLUDED.price,
    quantity=EXCLUDED.quantity,
    lastupdate=EXCLUDED.lastupdate
    where price!=EXCLUDED.price or quantity!=EXCLUDED.quantity;

我有以下错误 column reference "price" is ambiguous 我想知道如何解决这个问题?

5anewei6

5anewei61#

问题出在 where 条款。您需要限定列,以便有明确的:

INSERT INTO products(id,price,quantity,lastupdate)
SELECT id,price,quantity,lastupdate FROM tmp_products
ON CONFLICT (id) DO UPDATE SET
    price      = EXCLUDED.price,
    quantity   = EXCLUDED.quantity,
    lastupdate = EXCLUDED.lastupdate
WHERE products.price <> EXCLUDED.price OR products.quantity <> EXCLUDED.quantity;

请注意,还需要删除 SELECT ,否则您的查询不是有效的postgres sql,并将引发错误 INSERT has more target columns than expressions .

相关问题