SQL语句内部加入+其他...所以加入加入?

时间:2013-12-02 06:36:53

标签: mysql sql join

我有以下SQL语句,其中我添加了游戏库存和订购的库存,然后选择具有低于再订货点的总库存的游戏。唯一的问题是我还想在没有任何订购库存的再订货点下面选择游戏库存。我试着弄乱了ItemIDs不匹配的Having行,但没有运气。这是当前的工作代码。

我有什么:

SELECT tblGames.ItemID, tblGames.Title, ABS(tblGames.Inventory + Sum(tblSupplyOrders.Inventory)) AS UpdatedInventory
FROM tblGames
INNER JOIN tblSupplyOrders
ON tblGames.ItemID=tblSupplyOrders.ItemID
Group By tblGames.ItemID, tblGames.Title, tblGames.Inventory, tblGames.ReorderPoint
Having ABS(tblGames.Inventory + Sum(tblSupplyOrders.Inventory)) < tblGames.ReorderPoint

我还想用它显示:

SELECT tblGames.ItemID, tblGames.Title, tblGames.Inventory
FROM tblGames
INNER JOIN tblSupplyOrders
ON tblGames.ItemID=tblSupplyOrders.ItemID
Group By tblGames.ItemID, tblGames.Title, tblGames.Inventory, tblGames.ReorderPoint
Having tblGames.Inventory < tblGames.ReorderPoint

...没有tblSupplyOrders.ItemID

提前致谢!

更新请求

tblGames包括:

  • ItemID int,auto PK
  • 标题varchar(100)
  • Inventory int,
  • ReorderPoint int

tblSupplyOrders包括:

  • SupplyOrder int,auto PK
  • ItemID int,FK to tblGames
  • Inventory int

所以如果:

  • tblGames / tblSupplyOrders.ItemID =相同#
  • tblGames.Inventory = 2
  • tblSupplyOrders.Inventory = 3
  • tblGames.ReorderPoint = 6
  • 输出将包含此游戏。
  • 问题:如果tblSupplyOrders中没有匹配的ItemID,则不会检测到此游戏。

1 个答案:

答案 0 :(得分:2)

我认为你过于复杂了:

SELECT tg.ItemID, tg.Title, tg.Inventory
FROM tblGames tg
LEFT JOIN (
    select ItemID, sum(inventory) as Inventory
    from tblSupplyOrders 
    group by ItemID) tso
ON tg.ItemID=tso.ItemID
where tg.Inventory+coalesce(tso.Inventory,0) < tg.ReorderPoint

这会将tblGames连接到tblSupplyOrders的子查询,该子查询汇总特定项目的所有订单。这将返回tblGames中的所有行以及来自tblSupplyOrders的订单聚合的匹配行,其中没有匹配tso行的空值。

表达式tg.Inventory+coalesce(tso.Inventory,0)计算当前库存+挂单;需要coalesce来处理没有tso行的情况,对待处理的订单替换为零而不是null。