因此,对于我的库存系统,我有两个具有相同列名称的表(一个用于生产库存,另一个用于库存)。我想出了如何按产品对列进行分组,然后对数量求和。所以我想在两个表上运行此查询,然后从产品变量匹配的每个表中减去数量列。
我用它来添加组和总库存总数(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>";
答案 0 :(得分: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