2013-07-06 56 views
0

我加入產品和購物車表以計算每個購物車的總價格。這是我的SQL語句:來自派生列的MySQL總和()

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.是否有人知道我如何總結派生列的值?提前致謝。

+0

使用sum()函數 –

+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到,所以它是早期的評估,並應使查詢速度更快。

如果您希望在同一個查詢中使用new_unit_price和cart總數,則必須再次返回表中以獲取該數據。像這樣的東西應該工作:

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

如果我理解正確,則需要在一個查詢中爲每個產品計算的價格以及購物車的總價格。看到我上面編輯的答案。 –

+0

好的,謝謝。我已經得到了正確的值,並且我意識到這是我的傳球出錯了,這就是爲什麼值始終顯示爲0.0 –