【问题标题】:MySQL subtract from isolated subqueryMySQL 从孤立的子查询中减去
【发布时间】:2011-11-21 19:59:14
【问题描述】:

我有一个包含库存的表

ID   |   Product ID   |  In_Transit  |   Quantity   | Cumulative Quantity
=====+================+==============+==============+====================
1    |      1         |     0        |     1000     |      1000
2    |      1         |     0        |        1     |      1001
3    |      1         |     1        |       54     |      1055
4    |      1         |     1        |        1     |      1056

所以产品 id 1 的总库存是“1056”,我使用 SELECT MAX(ID) 子查询与表连接得到它的累积数量,即 1056。

我想获取库存总额(减去所有在途数量)

所以 1056 - 54 - 1 = 1001

我如何在一个查询中得到这个,所以我得到

Product ID | Total Inventory | Inventory on Hand (Excluding in Transit |
===========+=================+=========================================    
1          |     1056        |           1001

我还需要使用累积库存来获得总数,而不是“SUM”,除了对那些在途的求和,因为(那些不在途中的)有大量的记录,而且它们需要很长时间才能求和。我可以用它来汇总那些在途的,因为记录要少得多

【问题讨论】:

  • 您的数据库中是否确实存在累积数量列?这似乎是一种非常糟糕的形式。
  • 确实如此,它就像一个“缓存”,因为如果我要在最后一分钟对它们求和,那需要的时间太长了。记录太多了

标签: mysql join subquery


【解决方案1】:
SELECT 
    a.product_id
  , a.cumulative as total_inventory
  , a.cumulative - COALESCE(b.quantity,0) AS inventory_on_hand
FROM table1 a
JOIN 
    ( SELECT MAX(id) AS max_id
      FROM table1
      GROUP BY product_id
    ) m ON (m.max_id = a.id)
LEFT JOIN
    ( SELECT product_id, SUM(quantity) 
      FROM table1 
      WHERE in_transit = 1
      GROUP BY product_id
    ) b ON (a.product_id = b.product_id)

【讨论】:

  • 我认为如果找不到任何带有 in_transit = 1 的记录,我会得到空值
  • 我已经玩了一段时间了,我无法让它工作的原因是max(a.cumulative),它应该是max(id)记录中的cumulative_quantity )(因为累积数量也可以减少)
  • 这很好用!非常感谢,在此之前我一直在办公桌前用各种问题敲打我的头
  • 我将 SUM(quantity) 编辑为 SUM(quantity) 以使其工作
猜你喜欢
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
相关资源
最近更新 更多