0

Given the following table structures:

T1:

id a
1  1
2  2
3  3

T2:

id t1_id b
1  1     1
2  1     2
3  2     3

I need to add the value of t2.b to the value of t1.a where t2.t1_id = t1.id.

A simple update with a join like the following isn't working:

UPDATE t1
  JOIN t2 
    ON t2.t1_id = t1.id
   SET t1.a = t1.a + t2.b
 WHERE t2.id IN(1,2)

Expected T1 result (adds 1 and 2 to t1.a = 1; 3 to t1.a = 2):

id a
1  4
2  5
3  3

Actual T1 result (only adds 1 to t1.a = 1; 3 to t1.a = 2):

id a
1  2
2  5
3  3

At the moment I'm looking at a select that computes the full sum of values to be added using a group by, and then that result set is joined to the update... This seems like overkill for something so simple though! Does anyone have an elegant and efficient solution?

2
  • 1
    I think moving the join into a subselect at where clause should do the trick. Commented Jul 8, 2014 at 18:57
  • 1
    Problem is you have a one to many relationship from T1 - T2. You would only be adding an arbitrary single row from table 2 to the value from table 1. I can't think of a straight Join method of doing this off the top of my head. Commented Jul 8, 2014 at 19:08

1 Answer 1

1

Came up with this real quickly.

UPDATE T1 AS t
JOIN (
    SELECT
        t1_id, SUM(b) AS sum_total
    FROM
        T2
    WHERE
        t1_id IN (1, 2)
    GROUP BY
        T2.t1_id
) AS t2 ON t.id = t2.t1_id
SET  t.a =  t.a + t2.sum_total;
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that's the structure I had come to as well, was wondering if there's a 'nicer' way. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.