0

我有以下查询:

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 语句做某事。

建议?

4

3 回答 3

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

小提琴的链接

于 2013-09-16T21:20:42.110 回答
0

您可以计算购物车总数,但您想从group byand中删除一些列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

但个人价值观没有意义。

于 2013-09-16T21:30:18.603 回答
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

样本数据

于 2013-09-16T22:07:15.257 回答