分组后的mysql总和

时间:2017-01-27 15:46:52

标签: php mysql

购物车表:

itemid | amount 
------ | ------
1      | 2
2      | 4 

产品表:

itemid | Price
------ | ------
1      | 10
2      | 20

到目前为止我尝试过:

$cartPrice = 
"SELECT (SUM(products.Price) * SUM(cart.amount)) 
AS total_price 
FROM cart 
INNER JOIN products 
ON cart.itemid = products.itemid 
WHERE userid = '$IP' 
GROUP BY cart.itemid";

$Price = $mysqli->query($cartPrice);
$rowPrice = $Price->fetch_assoc();

echo "Total: ". $rowPrice['total_price'] ." ";

我的MYSQL查询输出以下内容:

total_price |
----------- | 
20          | 
80          | 

它将回应最后的结果。但我需要总共80 + 20.我该怎么做?

我现在得到的结果:

Total: 80

我想要的结果:

Total: 100

由于

3 个答案:

答案 0 :(得分:2)

您不必GROUP BY,因为您只想返回一行:

SELECT SUM(products.Price* cart.amount) AS total_price 
FROM cart 
INNER JOIN products 
ON cart.itemid = products.itemid 
WHERE userid = '$IP' 

答案 1 :(得分:1)

您可以SUM子查询的结果,如下所示:

SELECT SUM(total_price) as total_price FROM
(
    SELECT (SUM(products.Price) * SUM(cart.amount))  AS total_price 
    FROM cart 
    INNER JOIN products 
    ON cart.itemid = products.itemid 
    WHERE userid = '$IP' 
    GROUP BY cart.itemid
) total_prices

答案 2 :(得分:0)

一种简单的方法是使用带有第二个选择的并集而不使用

" SELECT (SUM(products.Price) * SUM(cart.amount))  AS total_price 
  FROM cart 
  INNER JOIN products 
  ON cart.itemid = products.itemid 
  WHERE userid = '$IP' 
  GROUP BY cart.itemid
  UNION 
  SELECT (SUM(products.Price) * SUM(cart.amount))  
  FROM cart 
  INNER JOIN products 
  ON cart.itemid = products.itemid 
  WHERE userid = '$IP' ";

第一次选择返回主要行,第二次返回最终总数