使用先前的变量增加变量

时间:2013-06-12 19:30:46

标签: php mysql

我尝试显示一天产生能量的曲线。所以曲线必须一直在增长。

我尝试增加变量" 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).

Bit 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);
}

感谢。

3 个答案:

答案 0 :(得分: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 :(得分:1)

在这里,我已经在查询

中创建了sum之前的值
SELECT id,(SELECT SUM(energie_journ) FROM `table` WHERE `id` <= p.`id`) AS  sum_col FROM `table` p

只使用我认为符合您需要的sum_col的结果

希望这是有道理的

答案 2 :(得分: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
相关问题