【问题标题】:How to select multiple items from a table based on certain cumulative amount?如何根据一定的累计金额从表中选择多个项目?
【发布时间】:2015-06-06 09:25:17
【问题描述】:

我有一个表名“食物”,有不同卡路里的食物。例如下面:

表:食物

id    name      calories
-----------------------
1     beef      200
2     tomato    400
3     carrot    500
4     nuts      800

我想要什么:当卡路里总和达到一定量时,我想根据卡路里量从表中选择多种食物,我想在那里停止查询并回显结果。例如,当我想要 600 卡路里时,前两种食物的结果将显示 200+400=600。当我希望卡路里限制为 1000 时,需要任何两种或两种以上卡路里量达到 1000 或接近 1000 的食物。 我已经尝试使用以下代码来实现它;但它不起作用。

SELECT * FROM foods WHERE SUM(calories)=1000 

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您可以使用变量来计算累积和:

    SELECT id, name, calories
    FROM (
       SELECT id, name, calories,
              @cumSum:= @cumSum + calories AS cumSum
       FROM foods, (SELECT @cumSum:=0) var
       ORDER BY id ) t
    WHERE cumSum <= 600   
    

    子查询计算累积和并将其值存储在@cumSum 变量中。然后外部查询可以使用计算列cumSum 过滤掉累积和大于600的结果。

    输出:

    id  name    calories
    ----------------------
    1   beef    200
    2   tomato  400
    

    Fiddle Demo here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 2017-09-28
      • 2018-03-21
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多