根据其他 table 的列更新 table w/ 冲突

Update table based on column from other table w/ on conflict

我在 Postgres 数据库中有两个 table。

Table一个

user quantity
mike 100
bob 200
alice 50

Table B

group user quantity
ace mike 10
beta mike 15
ace bob 2
omega bob 15
omega alice 25

我想更新 table b 并设置数量等于 table a 的数量 * 0.5 加入用户名 WHERE table b group = xyz。如果一个用户在tableb中不存在,我需要用组xyz,用户名,tablea的数量*0.5来创建它。

我这里有一些东西,但是当用户不存在于 tableb 中时它不会处理,我不确定它是否是 postgres 的正确语法。

update tablea
set quantity = tableb.quantity * 0.5
from tableb
where tablea.username = tableb.username
and tablea.group = ace

首先,在 table TableB 中为 "group""user" 列的组合添加一个唯一约束(如果它尚不存在):

ALTER TABLE TableB ADD CONSTRAINT un_group_user UNIQUE("group", "user");

然后就可以用INSERT语句插入TableATableB之间的用户,加上ON CONFLICT子句,使得存在的用户行TableB 中的组 'xyz' 将更新:

INSERT INTO TableB("group", "user", quantity)
SELECT 'xyz', "user", quantity / 2.0
FROM TableA
ON CONFLICT("group", "user") DO UPDATE SET
quantity = EXCLUDED.quantity;

参见demo