UPDATE user
SET balance = balance + p.amount
FROM payments p WHERE user.id = p.user_id AND p.id IN (36,38,40)
但它增加了余额,只有 1936 年第一笔付款的金额。 请帮助我如何修复它,我不想在代码中循环运行大量请求。
最佳答案
在多表 UPDATE
中,目标表中的每一行只更新一次,即使它被连接返回不止一次。
来自docs :
When a
FROM
clause is present, what essentially happens is that the target table is joined to the tables mentioned in the fromlist, and each output row of the join represents an update operation for the target table. When usingFROM
you should ensure that the join produces at most one output row for each row to be modified. In other words, a target row shouldn't join to more than one row from the other table(s). If it does, then only one of the join rows will be used to update the target row, but which one will be used is not readily predictable.
改用这个:
UPDATE user u
SET balance = balance + p.amount
FROM (
SELECT user_id, SUM(amount) AS amount
FROM payment
WHERE id IN (36, 38, 40)
GROUP BY
user_id
) p
WHERE u.id = p.user_id
关于PostgreSQL 更新 - 带有左连接问题的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4815694/