简体   繁体   English

MySQL:使用另一个表中的值在一个查询中多次更新同一行

[英]MySQL: Update same row multiple times in one query with values from another table

Given the following table structures: 给定以下表结构:

T1: T1:

id a
1  1
2  2
3  3

T2: 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 . 我需要的增值t2.b到的值t1.a其中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): 预期的T1结果(将1和2加到t1.a = 1;将3加到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): T1的实际结果(仅将1加到t1.a = 1;将3加到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! 目前,我正在寻找一个选择,该选择使用group by来计算要添加的值的总和,然后将该结果集加入到更新中……对于这么简单的事情,这似乎有些过头了! Does anyone have an elegant and efficient solution? 有谁有一个优雅而有效的解决方案?

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM