2014-10-01 32 views
0

我有四个表与计算领域的优化查询从多个表

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 

什么是最佳的查询,以实现与下列限制: 不能在DB 创建一个函数不能创建视图 我只能对数据库执行查询 感谢

+0

您需要使用JOIN。 – Arun 2014-10-01 13:40:15

+0

@popovitsj你是对的,我的不好,谢谢,我解决了这个问题。 – igx 2014-10-01 13:42:01

回答

1

我会建议与相关子查询这样做:

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(stored_id),itemsB(store_id)itemsC(store_id)

此优化的原因是因为它只需计算由limit选择的任意100个商店的值。而且,计算可以直接从索引完成。其他方法将需要对所有商店进行计算。

注意:通常在使用limit时,您需要一个order by子句。

1

没有商品的商店将不会显示此查询。如果这是一个要求,它将不得不稍微调整。

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 
+0

谢谢,但我确实需要空的商店以及... – igx 2014-10-01 14:02:02

+0

@igx我添加了一个额外的解决方案,应该处理。 – wvdz 2014-10-01 14:25:22

+0

@popvitsj谢谢! – igx 2014-10-02 10:59:56

0

如果我理解正确的话,你

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