2014-10-01 75 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