子查询销售和库存

时间:2017-08-30 19:42:52

标签: mysql sql

我有三个表:产品,库存和成分

Product Table    
ID[PK]        Name            Type
1         OrdinaryBurger     Burger
2         CheeseBurger       Burger
Inventory table
ID[PK]    Item_name    Stocks
100       Buns         5
101       Patties      5
103       Cheese       0
Ingredients table
ID[PK]      ProductID[FK]    InventoryID[FK]  Quantity
1001        1                  100            1
1002        1                  101            1
1003        2                  100            1
1004        2                  101            1
1005        2                  103            1

我想编写一个查询,如果连接的库存库存为0,则可以过滤所有不显示的产品,例如,这将不会显示Cheeseburger,因为奶酪库存为0.谢谢

1 个答案:

答案 0 :(得分:1)

以下内容仅返回至少含有足够成分的产品。

SELECT * FROM Products WHERE ProductID NOT IN (
    SELECT i.ProductID
    FROM Ingredients i
    JOIN Inventory iv ON i.InventoryID = iv.InventoryId
    GROUP BY i.ProductID, i.InventoryId
    HAVING SUM(iv.Stocks) < SUM(i.Quantity)
)
相关问题