在这里使用哪种类型的联接?

时间:2019-02-11 13:15:35

标签: mysql

我有两个表:StorageTransactionsFutureStockUsageMaterials

StorageTransactions表显示了产品进出存储库的所有移动,而FutureStockUsageMaterials表显示了产品进出该表的将来可能的移动。

我写了以下查询:

SELECT 
 SUM(StorageTransactions.Quantity) as CurrentStock, 
 COALESCE(FutureStockUsageMaterials.FutureStock, 0) as FutureStock,
 StorageTransactions.products_ProductId 
FROM StorageTransactions 
   LEFT JOIN FutureStockUsageMaterials 
   ON FutureStockUsageMaterials.products_ProductId = StorageTransactions.products_ProductId 
 GROUP BY StorageTransactions.products_ProductId`

例如,如果将来使用产品ID为3的产品,但是没有记录表明该产品存在于较早的交易中,我希望看到的是这样的一行:

CurrentStock  |  FutureStock  | products_ProductId
0             |  -325.00      | 3

此查询按预期方式工作,如显示3列,第一列是产品的当前库存,第二列是产品的未来库存,第三列是产品本身。我的问题是,当StorageTransactions表中没有给定产品的条目,但将来应该使用该产品时,由于连接,我想此查询不会返回该行。 / p>

我如何才能实现所需的行为,即得到将来将要使用的所有产品?

1 个答案:

答案 0 :(得分:2)

如果StorageTransactions的记录为空,但FutureStockUsageMaterials始终可用,则将LEFT JOIN更改为RIGHT JOIN

如果两个表的记录都可能为空,则您需要使用FULL OUTER JOIN,但不幸的是,mysql不支持FULL OUTER JOIN。因此,我们需要应用解决方法:

SELECT 
 SUM(StorageTransactions.Quantity) as CurrentStock, 
 COALESCE(FutureStockUsageMaterials.FutureStock, 0) as FutureStock,
 StorageTransactions.products_ProductId 
FROM StorageTransactions 
   LEFT JOIN FutureStockUsageMaterials 
   ON FutureStockUsageMaterials.products_ProductId = StorageTransactions.products_ProductId 
 GROUP BY StorageTransactions.products_ProductId`
UNION 
SELECT 
 SUM(StorageTransactions.Quantity) as CurrentStock, 
 COALESCE(FutureStockUsageMaterials.FutureStock, 0) as FutureStock,
 StorageTransactions.products_ProductId 
FROM StorageTransactions 
   RIGHT JOIN FutureStockUsageMaterials 
   ON FutureStockUsageMaterials.products_ProductId = StorageTransactions.products_ProductId 
 GROUP BY StorageTransactions.products_ProductId`