如何在同一表的SQL连接中使用值总和

时间:2019-03-05 10:58:49

标签: mysql sql

我正在尝试将数据库中的字段更新为其联接值的总和:

我有: 示例数据...

ID  reffer_id   my_refflink     s1  s2  m1  m2
1                      a                1   7
2      a               b                2   8
3      a               c                3   9
4                      d                4   0
5      b               e                5   1
6      c               f                6   2

我需要一个查询,将结果赋予s1和s2。

ID  reffer_id   my_refflink     s1   s2     m1  m2
1                      a         5   17     1   7
2      a               b         5   1      2   8
3      a               c         0   0      3   9
4                      d                    4   0
5      b               e         6   2      5   1
6      e               f         0   0      6   2

结果是

            s1= sum of m1 for reffer_id = my_refflink for each ID
            s2= sum of m2 for reffer_id = my_refflink for each ID

所以对于ID1:

将是

    s1 =5 because ID 2 and ID 3 have my_refflink of ID 1 and m1=2 m1=3
    s2 =17 because ID 2 and ID 3 have my_refflink of ID 1 and m2=8 m2=9

2 个答案:

答案 0 :(得分:1)

根据所使用的RDBMS,update / join语法可能有所不同,但以下查询适用于MySql

UPDATE someTable t
JOIN (SELECT reffer_id, SUM(m1) sum_m1, SUM(m2) sum_m2
      FROM someTable
      GROUP BY reffer_id) s ON s.reffer_id = t.my_refflink
 SET s1 = COALESCE(sum_m1, 0), s2 = COALESCE(sum_m2,0)

答案 1 :(得分:0)

您似乎想要一个join

select t.ID, t.reffer_id, t.my_refflink, tt.m1, tt.m2,
       t.m1, t.m2
from t left join
     (select reffer_id, sum(m1) as m1, sum(m2) as m2
      from t
      group by reffer_id
     ) tt
     on t.my_refflink = tt.reffer_id;

如果您想实际更改数据(而不是返回结果集),则update语法取决于您使用的数据库。