我正在尝试使用MYSQL中的ID添加价格总和。代码是这样的:-
SELECT SUM(products.price) AS sum FROM products WHERE products.id in (32,33,34)
让我们说id 32 = $ 2,id 33 = $ 4和id 34 = $ 5的价格是11美元,这是正确的。但是问题是当某些ID像这样时:-
SELECT SUM(products.price) AS sum FROM products WHERE products.id in (32,32,32)
当用户订购同一产品的3个时,总和为2美元,其应为6美元。我该如何解决?
答案 0 :(得分:0)
这是正确的语法:
SELECT
SUM(Total) AS Sum
FROM
(
SELECT
SUM(Price) / COUNT(Id) As Total
FROM products
WHERE products.Id IN (32)
GROUP BY products.Id
) AS table_price
答案 1 :(得分:-1)
您需要使用join
:
SELECT SUM(p.price) sum
FROM products p JOIN
(SELECT 32 as id UNION ALL SELECT 32 UNION ALL SELECT 32
) i
ON p.id = i.id;
请注意,通常WHERE
子句,尤其是IN
比较不能增加结果集中的行数。