2

因此,对于我的库存系统,我有两个具有相同列名称的表(一个用于生产的库存,一个用于发货的库存)。我想出了如何按产品对列进行分组,然后对数量求和。所以我想在两个表上运行这个查询,然后从产品变量匹配的每个表中减去数量列。

我用它来添加组和总库存总额(in):

 $query = "SELECT id, type, color, product, SUM(Quantity) AS TotalQuantity FROM inventory GROUP BY id, color, type";

我用它来分组和汇总库存货物(出):

$query = "SELECT id, type, color, product, SUM(Quantity) AS TotalQuantity FROM shipped GROUP BY id, color, type";

那么如何减去每个的数量列呢?

编辑:

我用它来输出:(一个表)

 echo '<tr><td>'. $row['product'] . '</td><td id="replace">' . $row['type'] . '</td><td>' . $row['color']. '</td><td>'. $row['TotalQuantity'];
 echo "</td></tr>";
4

1 回答 1

0

这可以完全在一个查询中完成。这些之间的一个INNER JOIN将允许您减去数量。id, color, product仅需要列表中的一个表中的列SELECT

SELECT
  inv.id, 
  inv.color,
  inv.product,
  /* total inventory quantity */
  SUM(inv.Quantity) AS TotalInvQuantity,
  /* total shipped quantity */
  SUM(ship.Quantity) AS TotalShipQuantity,
  /* inventory quantity minus shipped quantity */
  SUM(inv.Quantity) - COALESCE(SUM(ship.Quantity), 0) AS SubtractedQuantity
FROM
  inventory inv
  LEFT JOIN shipped ship ON inv.id = ship.id AND inv.color = ship.color AND inv.product = ship.product
GROUP BY
  inv.id,
  inv.color,
  inv.product

评论后更新

SELECT
  inv.id,
  inv.color,
  inv.product,
  inv.TotalInvQuantity, 
  COALESCE(ship.TotalShipQuantity, 0) AS TotalShipQuantity,
  inv.TotalQuantity - COALESCE(ship.TotalQuantity, 0) AS SubtractedQuantity
FROM (
    SELECT id, product, color, SUM(Quantity) AS TotalInvQuantity
    FROM inventory
    GROUP BY id, product, color
  ) inv
  LEFT JOIN (
    SELECT id, product, color, SUM(Quantity) AS TotalShipQuantity
    FROM inventory
    GROUP BY id, product, color
  ) ship ON 
      inv.id = ship.id 
      AND inv.product = ship.product 
      AND inv.color = ship.color
于 2012-06-17T02:41:14.773 回答