有没有一种方法可以从MySQL查询中计算总数?

时间:2020-03-28 09:41:58

标签: mysql

我正在尝试构建购物车系统。到目前为止,我可以通过一些联接轻松获取用户购物车数据,甚至可以根据用户在另一列中拥有的单价和数量来计算总价。但是,我想知道是否有一种方法可以直接计算直接来自SQL查询的总欠款。请允许我展示一个例子。这是我的桌子:

产品

product_id | product_name  | product_price  |  stock
1          | Pasta         | 10             |  50
2          | Bread         | 2              |  100

购物车

user_id  |  product_id  |  quantity
1        |  1           |  3
1        |  2           |  2

我当前的查询

SELECT
    `cart`.`product_id`,
    `cart`.`user_id`,
    `cart`.`quantity`,
    `products`.`product_price` as `unit_price`,
    `products`.`product_name`,
    `cart`.`quantity` * `products`.`product_price` as `Total`
FROM `cart`
INNER JOIN `products` ON `products`.`product_id` = `cart`.`product_id`
WHERE `cart`.`u_id` = 1;

如您所见,上面的查询将起作用,并向我返回特定用户购物车中的所有产品,并将Total列添加到结果中,并包含每个项目的总价。

现在,如果要计算总数,则必须读取PHP代码中的每一行并进行总数。尽管可以做到这一点,但我想知道MySQL是否有一种方法可以通过单个查询直接返回总计。

奖金问题:上面的购物车表结构足够好吗?

2 个答案:

答案 0 :(得分:0)

您可以在MYSQL中使用“ SUM”运算符直接从数据库获取值。 这是一个文档,您可以在其中获得更多信息: https://www.mysqltutorial.org/mysql-sum/ enter image description here

这里的代码是一个示例:

SELECT SUM(`cart`.`quantity` * `products`.`product_price`) as `CartTotal`
FROM `cart`
INNER JOIN `products` ON `products`.`product_id` = `cart`.`product_id`
WHERE `cart`.`u_id` = 1;

答案 1 :(得分:0)

您可以使用SUM聚合函数来计算购物车总费用。

SELECT SUM(`cart`.`quantity` * `products`.`product_price`) as `CartTotal`
FROM `cart`
INNER JOIN `products` ON `products`.`product_id` = `cart`.`product_id`
WHERE `cart`.`u_id` = 1;

您还可以使用UNION构造将购物车总结果合并到主要查询中,例如:

-- Get cart content for user
SELECT
    `cart`.`product_id`,
    `cart`.`user_id`,
    `cart`.`quantity`,
    `products`.`product_price` as `unit_price`,
    `products`.`product_name`,
    `cart`.`quantity` * `products`.`product_price` as `Total`
FROM `cart`
INNER JOIN `products` ON `products`.`product_id` = `cart`.`product_id`
WHERE `cart`.`u_id` = 1
UNION -- Union summary row to cart results
SELECT
    NULL as `product_id`, -- set NULL for non aggregated field
    `cart`.`user_id`,
    COUNT(*), -- calculate items count in cart
    NULL as `unit_price`, -- set NULL for non aggregated field
    'Total' as `product_name`, -- set 'Total' string as product name
    SUM(`cart`.`quantity` * `products`.`product_price`) as `CartTotal` -- calculate total cart cost
FROM `cart`
INNER JOIN `products` ON `products`.`product_id` = `cart`.`product_id`
WHERE `cart`.`u_id` = 1;
相关问题