将行添加到mysql请求中,并添加整体列


Adding row to mysql request with overall column

我在向相对较大的SELECT请求添加一个整体递增行时遇到了问题。表格看起来像:

+-----------+------------+
|   Date    |   Amount   |
+-----------+------------+
| 10:11:15  |     25     |
| 10:11:25  |     150    |
| 10:11:35  |     120    |
| 10:11:45  |      90    |
| 10:11:55  |     100    |
+-----------+------------+

我想添加一个新的列,其中包含该时间的总量,比如:

+-----------+------------+------------+
|   Date    |  Amount    |  Overall   |
+-----------+------------+------------+
| 10:11:15  |     25     |     25     |
| 10:11:25  |     150    |    175     |
| 10:11:35  |     120    |    295     |
| 10:11:45  |      90    |    385     |
| 10:11:55  |     100    |    485     |
+-----------+------------+------------+

该表是按时间排序的,因此最后一行将显示该时间戳之前的总金额。还找不到任何解决方案,如果你能帮忙,我会很高兴,所以我不必硬编码。

使用子选择来对项目+所有旧项目求和。

select Date, amount, (select sum(amount) from yourtable
                      where date <= t1.date) as Overall
from yourtable as t1

或者通过以下方式加入群组:

select t1.Date, t1.amount, sum(t2.amount)
from yourtable as t1 join yourtable as t2 on t2.date <= t1.date
group by t1.date, t1.amount

有两个地方可以做:

1、数据引擎:

可以对类似GetOverall_ForThisROw()的函数进行编码只做sum()where PKsome ID < something

2、编程语言:

你可以把它放在php代码中,我认为这可以保存数据库。

在我看来,从DB中获取原始数据,然后在php中运行一个简单的代码会给您带来最佳性能。