0

Im trying how to sum id by id two tables and update the one :

STOCKA

---------
|P | U |
|-------|
| 1 | 1 |
| 2 | 0 |
| 3 | 3 |
---------

STOCKB

--------- 
|P | U |
|-------|
| 1 | -3 |
| 2 | -2 |
| 3 | -1 |
---------

Results I want :

STOCKA

--------
|P | U |
|--------|
| 1 | -2 |
| 2 | -2 |
| 3 | 2 |
---------

My query :

UPDATE STOCKA,STOCKB
SET STOCKA.U =  STOCKA.U - ABS(STOCKB.U)
WHERE
STOCKA.P = STOCKB.P
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
sarasa
  • 15
  • 1
  • 5

2 Answers2

0

Use JOIN instead of trying to pass two tables in an UPDATE statement:

UPDATE STOCKA a
JOIN STOCKB b
    ON a.P = b.P
SET a.U =  a.U - ABS(b.U)
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

The query in your question should work, if there is only one row in the "b" table for each P. If there can be more than one row, then aggregate first and then join:

UPDATE STOCKA a join
       (select P, sum(abs(u)) as bu
        from STOCKB
        group by P
       ) b
       on a.P = b.P
    SET a.U =  a.U - b.bu;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786