Mysql 使用多个表中的计算字段优化查询
我有四张桌子Mysql 使用多个表中的计算字段优化查询,mysql,sql,Mysql,Sql,我有四张桌子 store[store_id(pk),name] itemsA(item_id(pk),store_id,name) itemB(item_id(pk),store_id,name) itemC(item_id(pk),store_id,name) 我想要一个查询来检索一个商店和他拥有的物品数量。比如: select s.store_id ,s.name,count() as numberOfItems from store limit 100 在以下限制条件下,实现这一目标的
store[store_id(pk),name]
itemsA(item_id(pk),store_id,name)
itemB(item_id(pk),store_id,name)
itemC(item_id(pk),store_id,name)
我想要一个查询来检索一个商店和他拥有的物品数量。比如:
select s.store_id ,s.name,count() as numberOfItems from store limit 100
在以下限制条件下,实现这一目标的最佳查询是什么:
无法在数据库中创建函数
无法创建视图
我只能在数据库上运行查询
谢谢此查询不会显示没有商品的门店。如果这是一个要求,它将不得不有所调整
SELECT s.store_id, COUNT(*)
FROM Store s
JOIN ItemA a ON a.store_id = s.store_id
JOIN ItemB b ON b.store_id = s.store_id
JOIN ItemC c ON c.store_id = s.store_id
GROUP BY s.store_id
一个简单的修改,也包括包含0项的存储:
SELECT s.store_id, COUNT(a.store_id) + COUNT(b.store_id) + COUNT(c.store_id)
FROM Store s
LEFT JOIN ItemA a ON a.store_id = s.store_id
LEFT JOIN ItemB b ON b.store_id = s.store_id
LEFT JOIN ItemC c ON c.store_id = s.store_id
GROUP BY s.store_id
如果我没听错的话
DECLARE @store TABLE (store_id INT, name NVARCHAR(100))
DECLARE @itemsA TABLE (item_id INT,store_id INT, name NVARCHAR(100))
DECLARE @itemsB TABLE (item_id INT,store_id INT, name NVARCHAR(100))
DECLARE @itemsC TABLE (item_id INT,store_id INT, name NVARCHAR(100))
INSERT INTO @store VALUES (1,'Store1')
INSERT INTO @store VALUES (2,'Store2')
INSERT INTO @itemsA VALUES (1,1,'itemsA_item1')
INSERT INTO @itemsA VALUES (2,1,'itemsA_item2')
INSERT INTO @itemsA VALUES (3,1,'itemsA_item3')
INSERT INTO @itemsB VALUES (1,2,'itemsB_item1')
INSERT INTO @itemsB VALUES (2,2,'itemsB_item2')
INSERT INTO @itemsB VALUES (3,2,'itemsB_item3')
INSERT INTO @itemsB VALUES (4,1,'itemsB_item4')
INSERT INTO @itemsC VALUES (1,3,'itemsC_item1')
INSERT INTO @itemsC VALUES (2,3,'itemsC_item2')
INSERT INTO @itemsC VALUES (3,2,'itemsC_item3')
SELECT TOP 100 store_id, SUM(HasItems) AS TotalItems FROM
(
SELECT store_id, COUNT(name) AS HasItems FROM @itemsA GROUP BY store_id
UNION
SELECT store_id, COUNT(name) AS HasItems FROM @itemsB GROUP BY store_id
UNION
SELECT store_id, COUNT(name) AS HasItems FROM @itemsC GROUP BY store_id
) AS StoreItems
GROUP BY store_id
我建议对相关子查询执行此操作:
select s.store_id, s.name,
((select count(*) from itemsA a where a.store_id = s.store_id) +
(select count(*) from itemsB b where b.store_id = s.store_id) +
(select count(*) from itemsC c where c.store_id = s.store_id)
) as numberOfItems
from store s
limit 100;
然后,您希望在每个项目表中都有一个索引:itemsA(存储的\u id)
,itemsB(存储的\u id)
,以及itemsC(存储的\u id)
之所以对其进行优化,是因为它只需计算由限制
选择的任意100个存储的值。并且,可以直接从该指数进行计算。其他方法需要对所有门店进行计算
注意:通常在使用
limit
时,您需要一个orderby
子句。您需要使用联接。@popovitsj您是对的,我的错,谢谢,我已经解决了。@igx我添加了一个额外的解决方案来处理这个问题。