繁体   English   中英

来自派生列的MySQL Sum()

[英]MySQL Sum() from derived column

我正在加入产品和购物车表格,以计算每个购物车的总价。 这是我的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。有人知道如何总结派生列的值吗? 提前致谢。

要使用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 "

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM