Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL UPDATE - query with left join problem

UPDATE user
SET balance = balance + p.amount 
FROM payments p WHERE user.id = p.user_id AND p.id IN (36,38,40)

But it adds to the balance, only the value amount of the first payment 1936. Please help me how to fix it, i do not want to make cycle in the code to run a lot of requests.

like image 584
Dmitro Avatar asked Jan 27 '11 11:01

Dmitro


People also ask

Can we use left join in update query?

To query data from related tables, you often use the join clauses, either inner join or left join. In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update. In this syntax: First, specify the name of the table (t1) that you want to update in the UPDATE clause.

Can we use join in update query in PostgreSQL?

Introduction to the PostgreSQL UPDATE join syntaxTo join to another table in the UPDATE statement, you specify the joined table in the FROM clause and provide the join condition in the WHERE clause. The FROM clause must appear immediately after the SET clause.

Are joins allowed in update statement?

The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.

How do you update data when joining two tables?

To UPDATE a table by joining multiple tables in SQL, let's create the two tables 'order' and 'order_detail. ' We can update the data of a table using conditions of other joined tables. It is possible to join two or more tables in an UPDATE query.


1 Answers

In a multiple-table UPDATE, each row in the target table is updated only once, even it's returned more than once by the join.

From the 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.

Use this instead:

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
like image 67
Quassnoi Avatar answered Nov 19 '22 03:11

Quassnoi