我有以下查询:
SELECT cb.customers_id, cb.products_id, p.products_model, pd.products_name, cb.customers_basket_quantity, p.products_price, (p.products_price * cb.customers_basket_quantity) AS product_total
FROM customers_basket cb, products p, products_description pd
WHERE cb.customers_id =194075
AND cb.products_id = pd.products_id
AND p.products_id = pd.products_id
我试图找出是否可以获得“cart_total”而无需进行其他查询,或者使用PHP来保持运行总计。
我不确定我是否可以使用CASE语句来做某事。
建议?
答案 0 :(得分:2)
SELECT cb.customers_id, cb.products_id, p.products_model, pd.products_name, cb.customers_basket_quantity, p.products_price, (p.products_price * cb.customers_basket_quantity) AS product_total,
(SELECT sum(p.products_price * cb.customers_basket_quantity)
FROM customers_basket cb, products p
WHERE cb.customers_id =194075
AND cb.products_id = p.products_id
group by cb.customers_id) AS cart_total
FROM customers_basket cb, products p, products_description pd
WHERE cb.customers_id =194075
AND cb.products_id = pd.products_id
AND p.products_id = pd.products_id
指向 Fiddle
的链接答案 1 :(得分:0)
您可以执行购物车总数,但是您想要删除group by
和select
中的某些列(它们不适合购物车级别)。您还应该使用标准的ANSI连接语法:
SELECT cb.customers_id, cb.customers_basket_quantity,
sum(p.products_price * cb.customers_basket_quantity) AS product_total
FROM customers_basket cb join
products p
on cb.products_id = p.products_id join
products_description pd
on p.products_id = pd.products_id
WHERE cb.customers_id = 194075
GROUP BY cb.customer_basket_id;
产品级别的信息在篮子级别没有意义。您可以创建产品名称列表,例如:
group_concat(p.products_name) as Products_Name
但是个人价值观没有意义。
答案 2 :(得分:0)
试试这个,你将得到查询最后一行的结果总和。
所有其他列都将为空。
SELECT cb.customers_id,
cb.products_id,
cb.customers_basket_quantity,
p.products_model,
p.products_price,
pd.products_name,
(p.products_price * cb.customers_basket_quantity) AS product_total,
null as cart_total
FROM products p
INNER JOIN customers_basket cb ON p.products_id = cb.products_id
INNER JOIN products_description pd ON pd.products_id = p.products_id
WHERE cb.customers_id = 194075
union all
SELECT null, null, null, null, null, null, null,
SUM(p.products_price * cb.customers_basket_quantity) AS cart_total
FROM products p
INNER JOIN customers_basket cb ON p.products_id = cb.products_id
WHERE cb.customers_id = 194075