I have two tables, “Hello” and “World”:
-
“Hello” has two columns id(int) and id1(int, default value 0)
-
“World” has column id2(int)
Whenever id = id2 I would like to +1 to id1.
I tried this using UPDATE like so
UPDATE "Hello" z1 set id1=z1.id1 + 1 FROM "World" z2 WHERE
z1.id = z2.id2
But that changed every column to 1 instead of adding 1 for every occurance of id=id2
After looking around for a solution it seems I need to use an aggregate function but
from previous posts I know that isn’t allowed within UPDATE.
I have a vague idea of one solution where I get the sum for id=id2 per id then put it in a temporary table and then UPDATE based on that value but I can’t seem to put it together so I’m thinking that might not be the best path to a solution?
Here’s what I did:
Initialization
Tables at the beginning
t1:
t2
Test case 1:
Result is what you described i.e. t1
I suspect the reason for this result is that in
z1.n + 1the value ofz1.nis determined only at the beginning and it is not updated as more rows match. This way the result is equivalent to the one you get by executing aSELECTselect *, t1.n + 1 from t1,t2 where t1.id = t2.id;Please note that every
UPDATEwill increment all values in n by one if there are at least one row for whicht1.id = t2.idis true.Test case 2:
Result was what you expected i.e. t1
Please note that the end result is same after each
UPDATEif the tablet2has not been modified.