我正在尝试编写一个查询,该查询将生成商家列表,然后计算他们拥有的库存物品数量以及每个库存物品的订单数量。商家,库存物品和订单都在不同的表格中。我期待回归看起来像这样:
Site | Inventory Items | Orders
London | 7282 | 1234996
Glasgow | 9829 | 734949
我可以通过此查询几乎立即获得网站和库存计数列表:
SELECT M.name AS 'Site',
COUNT(II.idInventoryItems) AS 'Inventory Items',
FROM Merchants M
JOIN
(SELECT idMerchants,
idInventoryItems
FROM InventoryItems) AS II ON II.idMerchants = M.idMerchants
GROUP BY M.name
我可以通过非常相似的查询获得网站和订单列表。但是当我将两者结合起来时,查询会无限期挂起,我必须取消查询。这是我一直在使用的完整查询:
SELECT M.name AS 'Site',
COUNT(II.idInventoryItems) AS 'Inventory Items',
COUNT(O.idOrders) AS 'Orders'
FROM Merchants M
JOIN
(SELECT idMerchants,
idInventoryItems
FROM InventoryItems) AS II ON II.idMerchants = M.idMerchants
JOIN
(SELECT idMerchants,
idOrders
FROM Orders) AS O ON O.idMerchants = M.idMerchants
GROUP BY M.name
我正在尝试用合理快速的查询实现的目标吗?如果是这样,我做错了什么?
答案 0 :(得分:2)
试试这个。将计数移动到派生表将为您提供连接所需的数据,并允许mysql使用idMerchants上的索引进行优化(如果它需要它用于性能目的)。然后,您将加入两个派生表,其中行数明显减少,这也将提高性能。
SELECT M.name AS 'Site',
II.count AS 'Inventory Items',
O.count as 'Orders'
FROM Merchants M
JOIN
(SELECT idMerchants, COUNT(idInventoryItems) AS 'count'
FROM InventoryItems GROUP BY idMerchants) AS II ON II.idMerchants = M.idMerchants
JOIN
(SELECT idMerchants,
COUNT(idOrders) AS 'count'
FROM Orders GROUP BY idMerchants) AS O ON O.idMerchants = M.idMerchants