【问题标题】:How to take sum of selected rows in mysql using where clause?如何使用 where 子句获取 mysql 中选定行的总和?
【发布时间】:2016-09-12 23:47:12
【问题描述】:

这是我的表,我想要一个选定产品的总和:

select sum(`price`) from add_product;

此查询对所有行都有效,但我想使用这样的 where 子句:

select sum(`price`) from add_product where product_id=1233 and product_id=1234;

如何做到这一点?

【问题讨论】:

  • 您在使用该查询时遇到了什么问题?
  • 我觉得你需要select sum(price) from add_product where product_id in (1233, 1234);

标签: mysql sql select sum


【解决方案1】:

使用BETWEENAND

对于 2 个'product_id'

SELECT SUM('price') FROM 'add_product' WHERE 'product_id' BETWEEN 1233 AND 1234

对于 3 个'product_id',按升序排列:

SELECT SUM('price') FROM 'add_product' WHERE 'product_id' BETWEEN 1233 AND 1235 ORDER BY 'product_id' ASC

【讨论】:

    【解决方案2】:

    首先, 纠正您的疑问,

    您的 productID 之间不能有 AND, 使用 OR 代替

        SELECT 
                SUM(`price`) 
        FROM 
                add_product 
        WHERE
                product_id=1233 OR product_id=1234; 
    

    你也可以使用 IN 子句,

    http://www.tutorialspoint.com/mysql/mysql-in-clause.htm

    或者,如果您需要按产品求和,则使用 GROUP BY,

    http://www.tutorialspoint.com/mysql/mysql-group-by-clause.htm

        SELECT 
                product_id, SUM(`price`) totprice
        FROM 
                add_product 
        WHERE
                product_id IN (1233,1234)
        GROUP BY
                product_id;
    

    【讨论】:

      【解决方案3】:

      您可以将 in 用于多个值,而不是使用 OR。

      select sum(`price`) from add_product where product_id in (1233,1234);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-20
        • 2015-10-26
        • 1970-01-01
        相关资源
        最近更新 更多