dsjq62428 2016-09-11 16:36
浏览 5

在mysql SELECT中运行总计

Thank you for all the examples and help for the running totals. Apparently I have missed something:

<?php
include 'connect.php';
$tdebit=0;
$tcredit=0;
$sql = <<<SQL
SELECT  ...., ($tdebit=$tdebit+debit) AS tdebit,
($tcredit=$tcredit+credit)  AS tcredit  
FROM accounting
SQL;

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}
$items = array();
while($row = $result->fetch_assoc()){   
    array_push($items, $row);
}
echo json_encode($items);
mysqli_close($con);
?>

The result is 1 if a value in the field (credit/debit) and 0 if the value is zero. Any 'SET' or ':=' is not supported, the query is just not executed.

Thanks for any help, JPB

  • 写回答

1条回答 默认 最新

  • dqz30992 2016-09-11 16:43
    关注

    For the running total, you need a variable in the database, not the application layer.

    So:

    SELECT ....,
          (@tdebit := @tdebit + debit) AS tdebit,
          (@tcredit := @tcredit + credit) AS tcredit  
    FROM accounting CROSS JOIN
         (SELECT @tcredit := 0, @tdebit := 0) params
    ORDER BY ??;
    

    Normally, when calculating a running total, you want the accumulation to be in a particular order. SQL result sets are not guaranteed to be in a particular order unless you specify an ORDRE BY clause. The ?? is for you to insert the appropriate column.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大