来自派生列的MySQL Sum()

时间:2013-07-06 05:15:03

标签: mysql sum

我正在加入产品和购物车表来计算每个购物车的总价。这是我的sql语句:

 String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity, p.productPrice * c.quantity as new_unit_price, SUM(p.productPrice * c.quantity) AS totalPrice"
                + " FROM sm_product p INNER JOIN sm_cart c "
                + "ON p.productID = c.productID"
                + " WHERE c.custName = '" + custName + "'";

我通过将购物车表中的数量乘以产品表中的产品价格来派生名为new_unit_price的列。然后我想使用new_unit_price的派生列来总结购物车中所有商品的价格。我通过以下方式从数据库中的列中获取数据:

double subItemTotal = rs.getDouble("new_unit_price");
double totalPrice = rs.getDouble("totalPrice");

我的new_unit_price有效。但不幸的是,我的总和不起作用。它仍然是0.有人知道如何总结派生列的值?提前谢谢。

1 个答案:

答案 0 :(得分:0)

要使用SUM()函数,您需要在语句结束时执行GROUP BY。

这应该会得到您的整体购物车总数:

 String sql = "SELECT c.custname "
+ ", SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " AND c.custName = '" + custName + "'"
+ " GROUP BY c.custname;"

此外,我将WHERE更改为AND,因此它会在之前进行评估,并且应该使查询更快。

如果您想在同一查询中使用new_unit_price和购物车总额,则必须再次返回表格以获取该数据。这样的事情应该有效:

 String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity "
+ ", p.productPrice * c.quantity as new_unit_price, total.totalPrice FROM "
+ "( "
    + "SELECT c.custname "
    + ", SUM(p.productPrice * c.quantity) AS totalPrice"
    + " FROM sm_product p INNER JOIN sm_cart c "
    + "ON p.productID = c.productID"
    + " AND c.custName = '" + custName + "'"
    + " GROUP BY c.custname"
+ ") AS total "
+ "INNER JOIN sm_cart c "
+ "ON total.custname=c.custname "
+ "INNER JOIN sm_product p "
+ "ON p.productID = c.productID "