从WHERE条件的所有行的SUM?

问题描述 投票:2回答:5

我试图添加从查询检索到的所有行的内容。

到目前为止,我曾尝试:

$totalquery = "SELECT SUM(catalogue.price) AS fCount
        FROM catalogue LEFT JOIN orders ON catalogue.plantid = orders.orderplantid
        WHERE orders.orderplantid = '$actualresult' AND orders.ordercustomerid = '$actualresult2' GROUP BY catalogue.price";
        $result3 = mysql_query($totalquery) or die ("Query failed : " . mysql_error());
        $totalresult = mysql_result($result3,0);

然后呼应了$ totalresult,但问题是只显示最后一个值,而不是所有选择的值的总和 - 在我要去哪里不对任何想法?

php mysql
5个回答
2
投票

从行的末尾删除GROUP BY catalogue.price;总和命令是aggregate functions之一。


1
投票

如果形成在多个组分组的结果,你需要找回在一个循环中的行:

while($row = mysql_fetch_assoc($result3)) {
    $total = $row['fCount'];
    ... do something with total ...
}

目前的情况是,你只取第一总和值和扔掉的休息。


0
投票

最有可能的,因为有多个结果,而不只是一个。因为你不通过数组循环和存储所有的值来查看,所有你看到的是结果集的最后一个值,因为这是最后分配OT了$ totalresult变量...

尝试mysql_fetch_assoc($ result3)或mysql_fetch_array($ result3)和遍历结果让所有返回的信息...


0
投票

尝试删除GROUP BY声明。

另外,如果$actualresult$actualresult2是从用户输入时,一定要逃避这些,以避免SQL注入攻击:

$totalquery= "... WHERE orders.orderplantid = '" . mysql_real_escape_string($actualresult) . "' AND orders.ordercustomerid = '" . mysql_real_escape_string($actualresult2) . "'";

0
投票

而不是mysql_result()使用mysql_fetch_array()

© www.soinside.com 2019 - 2024. All rights reserved.