2013-06-12 235 views
2

我试图显示一天的能源产生的曲线。所以曲线必须始终在增长。增加一个变量与以前的

我尝试增加变量“energie_journ”我以前的所有mysql数据库。

例:

MySQL的:

ID   energie_journ 
1     5 
2     5 
3     10 
4     6 

期望的结果:

First energie_journ = 1, the second = 10 (5 +5), third = 20 (5 +5 +10), fourth = 26 (5 +5 +10 +6). 

位PHP:

while ($row2 = mysql_fetch_array($result2)) { 
    extract($row2); 

    $datetime *= 1000; 

    $encode_energie_journ[] = array((float)$datetime, (float)$energie_journ == null ? null : (float)$energie_journ); 
} 

感谢。

+0

您应该将_每行值添加到累加器变量。 – alexis

回答

1

在这里你走我已经在查询中所做的以前值的sum

SELECT id,(SELECT SUM(energie_journ) FROM `table` WHERE `id` <= p.`id`) AS sum_col FROM `table` p 

只是使用的sum_col,我认为是按照您的需求

希望这是有道理的

+0

谢谢!我用你的方法,这个更快! – GyGyt

1

试试这样说:

$energy_journ = 0; 
while ($row = mysql_fetch_array($result2)) { 
    $energy_journ += $row[1]; 
    // now save this value to an array, if that's what you are after. 
} 

,并避免使用extract,这将让你头疼的问题。

1
结果

你也可以让MySQL为你计算:

SELECT 
    ID, 
    energie_journ, 
    @subtot := @subtot + val AS energie_journ_to_date 
FROM myTable, (SELECT @subtot := 0) subtots 
ORDER BY ID; 

结果将如下所示:

ID  energie_journ energie_journ_to_date 
1    5     5 
2    5     10 
3   10     20 
4    6     26