返回单列之和构成一定值的行

时间:2019-12-26 09:08:05

标签: mysql mysql-variables

我有一张桌子。它具有以下结构

goods_receiving_items

  • id
  • item_id
  • 数量
  • created_at

我正在尝试获取具有以下条件的行

  • 有一个item_id

  • 当数量列的总和等于某个值

例如,我有以下数据

const TabBlock: React.FC<TBlock> = ({ 
    component,
    params,
    ...props
}) => {
    const LazyComponent = useMemo(() => component, [component]);

    return (
        <Suspense fallback={<div>Loading...</div>}>
             <LazyComponent  {...params} />
        </Suspense>
    )
}

我尝试了以下查询:

+----+---------+----------+------------+
| id | item_id | quantity | created_at |
+----+---------+----------+------------+
|  1 |       2 |       11 | 2019-10-10 |
|  2 |       3 |      110 | 2019-10-11 |
|  3 |       2 |       20 | 2019-11-09 |
|  4 |       2 |        5 | 2019-11-10 |
|  5 |       2 |        1 | 2019-11-11 |
+----+---------+----------+------------+

如果我不使用SET @sum:= 0; SELECT item_id, created_at, (@sum:= @sum + quantity) AS SUM, quantity FROM goods_receiving_items WHERE item_id = 2 AND @sum<= 6 ORDER BY created_at DESC ,那么查询将给我ID'1'。但是,如果我使用ORDER BY,它将返回所有带有ORDER BY的行。

应返回的ID分别为“ 5”和“ 4”

我似乎无法解决这个问题,item_id = 2对我的任务至关重要。 任何帮助将不胜感激

3 个答案:

答案 0 :(得分:1)

您应该在结果集上使用order by 您可以使用子查询

container_name

答案 1 :(得分:0)

您应尝试使用INNER JOINSELECT min(created_at)的{​​{1}}

从MYSQL文档:

  

...从每个组中选择值不受以下因素影响   添加一个ORDER BY子句。结果集的排序发生在   值已被选择,并且ORDER BY不会影响   服务器选择。

以下问题的答案可能会更详细:MYSQL GROUP BY and ORDER BY not working together as expected

答案 2 :(得分:0)

搜索后,我组成了以下查询

SELECT 
t.id, t.quantity, t.created_at, t.sum
      FROM 
       ( SELECT 
          *,
          @bal := @bal + quantity AS sum,
          IF(@bal >= $search_number, @doneHere := @doneHere + 1 , @doneHere) AS whereToStop
            FROM goods_receiving_items
            CROSS JOIN (SELECT @bal := 0.0 , @doneHere := 0) var
            WHERE item_id = $item_id
            ORDER BY created_at DESC) AS t
                    WHERE t.whereToStop <= 1
                    ORDER BY t.created_at ASC

在上面的查询中,$ search_number是一个变量,其中包含必须达到的值。 $ item_id是我们要搜索的项目。

这将返回所有由数量列构成的总和的行。该总和将按created_at的降序排列,然后按升序重新排列。

当库存管理系统中使用了一定数量的物料时,我使用此查询来计算成本;因此这可能会帮助其他人做同样的事情。我从StackOverflow

上的另一个question那里获取了大部分查询