【问题标题】:MySQL Sum() from derived columnMySQL Sum() 来自派生列
【发布时间】:2013-07-06 05:15:03
【问题描述】:

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

【问题讨论】:

  • 这就是我所做的,但它什么也没显示

标签: mysql sum


【解决方案1】:

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

【讨论】:

  • 但我需要一个派生列,即子项目总价。我无法删除它。总和只会总结总价或小计价的派生列
  • 如果我的理解正确,您希望在一次查询中计算出每种产品的价格以及购物车的总价格。请参阅上面我编辑的答案。
  • 好的,谢谢。我已经得到了正确的值,我意识到这是我的传递出错了,这就是为什么值总是显示 0.0
猜你喜欢
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
相关资源
最近更新 更多