2013-06-12 268 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