简体   繁体   English

来自派生列的MySQL Sum()

[英]MySQL Sum() from derived column

I am joining product and cart table to calculate for the total price for each cart. 我正在加入产品和购物车表格,以计算每个购物车的总价。 Here is my sql statement: 这是我的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 + "'";

I derived a column named new_unit_price by multiplying the quantity from cart table and product price from product table. 我通过将购物车表中的数量与产品表中的产品价格相乘,得出了名为new_unit_price的列。 Then I want to use the derived column which is new_unit_price to sum up the price of all item in the cart. 然后,我想使用派生列new_unit_price来汇总购物车中所有项目的价格。 I get the data from the column in database by: 我通过以下方式从数据库的列中获取数据:

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

My new_unit_price works. 我的new_unit_price有效。 But unfortunately, my sum does not works. 但不幸的是,我的总和没有用。 It's still 0. Does anybody know how can I sum up the value from derived column? 它仍然是0。有人知道如何总结派生列的值吗? Thanks in advance. 提前致谢。

To use the SUM() function, you'll need to do a GROUP BY at the end of your statement. 要使用SUM()函数,您需要在语句末尾执行GROUP BY。

This should get your overall cart total: 这应该使您的购物车总数达到:

 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;"

Also, I changed the WHERE to an AND so it is evaluated earlier and should make the query faster. 另外,我将WHERE更改为AND,因此可以较早地对其求值,并且应该使查询速度更快。

If you want the new_unit_price and the cart total in the same query, you have to go back into the tables again to get that data. 如果您希望在同一查询中获得new_unit_price和购物车总计,则必须再次回到表中以获取该数据。 Something like this should work: 这样的事情应该起作用:

 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