来自派生列的MySQL Sum()

来自派生列的MySQL Sum(),mysql,sum,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 INNE

我加入产品和购物车表来计算每个购物车的总价格。以下是我的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 + "'";
通过将cart表中的数量和product表中的product price相乘,我得到了一个名为new_unit_price的列。然后我想使用派生列,即新的单位价格,来汇总购物车中所有商品的价格。我通过以下方式从数据库中的列中获取数据:

double subItemTotal = rs.getDouble("new_unit_price");
double totalPrice = rs.getDouble("totalPrice");
我的新单价有效。但不幸的是,我的总数不起作用。还是0。有人知道如何从派生列求和值吗?提前感谢。

要使用SUM()函数,您需要在语句末尾进行分组

这将得到您的购物车总数:

 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改为an,因此它会更早地进行计算,应该会使查询更快

如果希望在同一查询中获得新的单价和购物车总价,则必须再次返回表以获取该数据。像这样的方法应该会奏效:

 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 "

这就是我所做的,但它没有显示任何东西,但我需要一个派生列,这是分项总价。我无法移除它。如果我理解正确的话,总和将只对总价或派生列进行总和。您希望在一次查询中得到每个产品的计算价格以及购物车的总价。请看我上面编辑的答案。好的,谢谢。我已经得到了正确的数值,我意识到这是我的传球出错了,这就是为什么数值总是显示为0.0