Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有任何MySQL查询来更新/替换Group By table点到其他MySQL表中_Mysql_Group By_Sql Update_Mysqlupgrade - Fatal编程技术网

有任何MySQL查询来更新/替换Group By table点到其他MySQL表中

有任何MySQL查询来更新/替换Group By table点到其他MySQL表中,mysql,group-by,sql-update,mysqlupgrade,Mysql,Group By,Sql Update,Mysqlupgrade,我使用下面的查询过滤My(TableA-字段应用程序id、用户id、点、tr类型、说明) select app_id, user_id,sum(case when tr_type = 'add' then points when tr_type = 'sub' then - points end) as points from TableA group by app_id, user_id; 结果: app_id user_id points 1 1a 10 1

我使用下面的查询过滤My(TableA-字段应用程序id、用户id、点、tr类型、说明

select app_id, user_id,sum(case when tr_type = 'add' then points when tr_type = 'sub' then - points end) as points
from TableA
group by app_id, user_id;
结果:

app_id  user_id  points
1          1a      10
1          1b      12
1          1c      3
现在我有另一张桌子(表B)


现在我需要快速替换查询来更新TableB点值,它是TableA中的groupby

您可以使用一个内部连接和子查询来更新groupby值

update tableB b
INNER JOIN (
    select app_id
        , user_id
        ,sum(case when tr_type = 'add' then points when tr_type = 'sub' then - points end) as points
    from TableA
    group by app_id, user_id

) t ON t.app_id = b.app_id
    AND t.user_id = b.user_id 
set b.points = t.points 

如果您可以查询一个数字,那么最好这样做,而不是将总数保存在表中,因为它们几乎总是错误的。某个地方的人会快速修复数据库,忘记维护总数
update tableB b
INNER JOIN (
    select app_id
        , user_id
        ,sum(case when tr_type = 'add' then points when tr_type = 'sub' then - points end) as points
    from TableA
    group by app_id, user_id

) t ON t.app_id = b.app_id
    AND t.user_id = b.user_id 
set b.points = t.points