如何在 MySQL 中将小计添加到 table?

How can I add subtotal to table in MySQL?

假设我的 table 如下所示:

id    count    sub_total
1     10       NULL
2     15       NULL
3     10       NULL
4     25       NULL

如何将此 table 更新为如下所示?

id    count    sub_total
1     10       10
2     15       25
3     10       35
4     25       60 

我可以在应用层很容易地做到这一点。但我想在 MySQL 中学习如何做。我一直在尝试使用 SUM(CASE WHEN... 和其他分组进行多种变体,但均无济于事。

如果您的 id 字段是连续的并且在增长,那么相关子查询是一种方式:

select *, (select sum(count) from t where t.id <= t1.id) 
from t t1

或作为连接:

select t1.id, t1.count, sum(t2.count)
from t t1
join t t2 on t2.id <= t1.id
group by t1.id, t1.count
order by t1.id

要更新您的 table(假设列 sub_total 已经存在):

update t 
join (
  select t1.id, sum(t2.count) st
  from t t1
  join t t2 on t2.id <= t1.id
  group by t1.id
) t3 on t.id = t3.id
set t.sub_total = t3.st;

Sample SQL Fiddle 显示更新。