在mysql SELECT中运行总计

时间:2016-09-11 16:36:54

标签: php mysql

感谢您提供运行总计的所有示例和帮助。 显然我错过了一些东西:

<?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);
?>

如果字段中的值(信用/借记),则结果为1;如果值为零,则结果为0。 不支持任何“SET”或“:=”,只是不执行查询。

感谢任何帮助,JPB

1 个答案:

答案 0 :(得分:0)

对于运行总计,您需要数据库中的变量,而不是应用程序层。

所以:

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

通常,在计算运行总计时,您希望累积按特定顺序排列。除非指定ORDRE BY子句,否则不保证SQL结果集具有特定顺序。 ??用于插入相应的列。