基于点匹配的{id}匹配,根据另一个更新一个MySQL表值

时间:2017-03-16 08:55:14

标签: mysql sql

我正在尝试从一个表(user_tranz)中获取值的聚合,并希望根据(用户的ID >来存储以更新/插入另一个表(用户) strong>在 user_tranz 中找到 有这两个mysql表结构:

1-用户:

    id      coin  buy  added  free   pay_later  renewed   pro
=========== ==== ===== ====== ==== =========== ========== ===
          1 0     0      0     0       0           0       0
          2 0     0      0     0       0           0       0
          3 0     0      0     0       0           0       0

2- user_tranz:

  id (AI)     user_id coin  buy  added  free   pay_later  renewed   pro
========== =========== ==== ===== ====== ==== =========== ========== ===
       99           1    10   5      10     10       20           50     100
       98           2    5    5      10     10       20           50     10
       97           3    5    5      10     10       20           50     25
       96           3    0    0      10     10       20           50     10
       95           3    10   5      0      0        20           50     5
       94           2    10   5      10     10       20           50     10 

到目前为止,我知道这可以通过类似(LEFT JOIN with COALESCE())之类的东西来完成,但我不知道如何使用join <一次存储多个值来聚合值< / p>

  

预期结果:

Users:
    id      coin  buy  added  free   pay_later  renewed   pro
=========== ==== ===== ====== ==== =========== ========== ===
    1        10    5     10    10      20         50      100
    2        15    10    20    20      40        100      20
    3        15    10    20    20      60        150      40

1 个答案:

答案 0 :(得分:0)

这个怎么样:

UPDATE users u 
SET u.coin = (
    SELECT SUM(ut.coin) 
    FROM user_tranz ut 
    WHERE ut.user_id = u.id
), ...

您可以使用子查询来确定要在更新查询中插入的值。