0

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?

1
  • I don't think you need aggregates. How do you know that all of the id's were not zero before the query?. Your query looks like it should it work to me. Maybe a column is mixed up or something like that.
    – nate c
    Apr 3, 2011 at 3:07

1 Answer 1

0

Here's what I did:

Initialization

create table t1 (id int, n int default 0);
create table t2 (id int);

insert into t1 values (1), (2), (3);
insert into t2 values (1), (2), (2), (3), (3), (3);

Tables at the beginning

t1:

id ; n
1  ; 0
2  ; 0 
3  ; 0

t2

id
1
2
2
3
3
3

Test case 1:

update t1 z1 set n = z1.n + 1 from t2 z2 where z1.id = z2.id;

Result is what you described i.e. t1

id ; n
1  ; 1
2  ; 1 
3  ; 1

I suspect the reason for this result is that in z1.n + 1 the value of z1.n is 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 a SELECT select *, t1.n + 1 from t1,t2 where t1.id = t2.id;

Please note that every UPDATE will increment all values in n by one if there are at least one row for which t1.id = t2.id is true.

Test case 2:

update t1 set n = (select count(*) from t2 where t2.id = t1.id)

Result was what you expected i.e. t1

id ; n
1  ; 1
2  ; 2 
3  ; 3

Please note that the end result is same after each UPDATE if the table t2 has not been modified.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.