MySql -计数从开始直到每一天


MySql - count from beginning until each day

假设我有下面的表(记住这个表将有10000+行):

id    total           date
1       5        2015-05-16
2       8        2015-05-17
3       4        2015-05-18
4       9        2015-05-19
5       3        2015-05-20

我希望查询给出以下结果:

1
date => 2015-05-16
total => 5
2
date => 2015-05-17
total => 13
3
date => 2015-05-18
total => 17
4
date => 2015-05-19
total => 26
5
date => 2015-05-20
total -> 29

我现在想不出任何可以这样做的查询,这就是为什么我没有提供任何我尝试过的代码。

任何想法吗?我不确定如果这是可能的只有mysql,也许我必须使用和php.

这可以在mysql中使用用户定义的变量来完成,然后得到运行总数

select
id,
total,
date
date from
(
 select
 id,
 @tot:= @tot+total as total,
 date from my_table,(select @tot:=0)x
 order by date
)x

你可以这样做-

SELECT 
     a.id, 
     a.date, 
    (SELECT SUM(b.total) FROM your_table WHERE b.date <= a.date) as new_total       
FROM your_table a, your_table b 
ORDER BY a.date ASC

应该这样做:

select id, (select sum(total) from table a where a.date <= b.date)  from table b