循环中的SUM - MYSQL

时间:2015-02-03 03:42:27

标签: php mysql

我有那些表:

alltransations

enter image description here

alladdon_list

enter image description here

我只想简单sum将所有插件简化为transac_id,将group简化为guest_id,以便我可以得到结果:

enter image description here

但是我的query

<table border=1 cellpadding=5 >
    <tr>
        <th>Names</th>
        <th>Amount</th>
    </tr>

<?php

include("conn_archive.php");

$cfaddontotal = 0;

$getall = mysql_query("SELECT *, sum(quantity) as quantity,price
                        FROM alltransactions at, alladdon_list aal
                        WHERE at.transac_id=aal.aatransac_id
                        GROUP BY guest_id
                        ", $db2);
while($rows = mysql_fetch_assoc($getall)){
        // GUEST INFO
        $guest_fname = $rows['guest_fname'];
        $guest_lname = $rows['guest_lname'];

        // ADDON INFO
        $addondesc = $rows['description'];
        $addondate = $rows['datef'];
        $addonqty = $rows['quantity'];
        $addonprice = $rows['price'];
        $addontcost = $addonprice * $addonqty; // cost of specific product
        $cfaddontotal += $addonprice * $addonqty; // total cost of all products

        echo "<tr>";
        echo "<td>$guest_fname $guest_lname</td>";
        echo "<td>&#8369; ".number_format($addontcost)."</td>";
        echo "</tr>";
}

?>
<tr>
    <th colspan=2 >Total Addon Cost: &#8369; <?php echo number_format($cfaddontotal); ?></th>
</tr>
</table>

我得到了这个(这是错误的):

enter image description here

无法确定用于获得准确计算的query

1 个答案:

答案 0 :(得分:2)

您的代码令人困惑。您是所有产品的总和(具有不同的价格)并乘以一个&#34;随机&#34;价格(如果group by选择不包含没有聚合函数的字段会很好:MySQL Handling of GROUP BY)。

最好将查询更改为

SELECT *, sum(quantity*price) as total
                    FROM alltransactions at, alladdon_list aal
                    WHERE at.transac_id=aal.aatransac_id
                    GROUP BY guest_id