当它应该是xxx量时,SELECT SUM()总是返回0

时间:2015-02-14 19:19:08

标签: php mysql

需要帮助SELECT SUM()...这是我的所有查询,无论什么时候运行结果总是0任何正文看到我的问题似乎无法弄清楚...

$data = $db->query("SELECT SUM(credit_amount) FROM a_creditpurchase");

$creditsbought = 0;
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
    $creditsbought += $row['credit_amount'];
}
echo $creditsbought;

3 个答案:

答案 0 :(得分:0)

试试这个

$data = $db->query("SELECT SUM(credit_amount) as sum FROM a_creditpurchase");

$creditsbought = 0;
$row = $data->fetch(PDO::FETCH_ASSOC);
$creditsbought = $row['sum'];

echo $creditsbought;

答案 1 :(得分:0)

您是否尝试过GROUP(credit_amount)的SQL查询?

$data = $db->query("SELECT SUM(credit_amount) FROM a_creditpurchase GROUP(credit_amount)");

答案 2 :(得分:0)

这非常有效,谢谢

$data = $db->query("SELECT SUM(credit_amount) as totalAmount FROM a_creditpurchase");

while($row = $data->fetch(PDO::FETCH_ASSOC)) {
$creditsbought += $row['totalAmount'];
}