PostgreSQL 更新 - 带有左连接问题的查询

标签 postgresql left-join

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 using FROM 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/

相关文章:

mysql - 通过多个子查询连接优化查询

sql - 如何将一个表中的新记录插入到另一个表中

java - 如何配置连接池 Apache Tomcat->PostgreSQL->Persistence Java?

mysql - 将 Rails ActiveRecord GROUP 查询从 MySQL 转换为 PostgreSQL

mysql - 离开加入具体条件请帮助

php - 将列添加到一个表中,该表是另一个表的 COUNT

mysql - 如何从另一个表中的字段获取计数 - MySQL

postgresql - Postgres "reverse count(*)"(不稳定?)

sql - PSQL 查询问题我如何对这些结果进行分组。里面的错误信息

python - 与 SQLAlchemy-Continuum 的多对多关系插入具有重复 transaction_id 的记录