有任何MySQL查询来更新/替换Group By table点到其他MySQL表中
我使用下面的查询过滤My(TableA-字段应用程序id、用户id、点、tr类型、说明)有任何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
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