2012-08-24 212 views
-1

我有一個需要很長時間執行的查詢。我曾嘗試在每張桌上玩索引,但仍然需要很長時間。有沒有其他的方法來優化這個查詢?優化SQL查詢

SELECT tblDLM.Phone 
FROM (SELECT Table1.Phone, 
       Count(Table_1.T1ID) AS CountOfT1ID 
     FROM Table_1 
       INNER JOIN Table_2 
       ON Table_1.SubscriptionID = Table_2.SubscriptionID 
     WHERE ((Table_1.MsgType) = 'coupon') 
       AND (((Table_1.Phone) IN (SELECT DISTINCT Table_3.Phone 
              FROM Table_3 
              WHERE Table_3.DeliveryStatus <> 0 
                AND Table1.Phone = Table_3.Phone) 
         AND CampaignID <> Cast(@intCampaignIDTemp AS NVARCHAR(50)))) 
     GROUP BY Table_1.Phone, 
        Table_2.MasterServiceID 
     HAVING Table_2.MasterServiceID = 121) tblDLM 
WHERE CountOfT1ID >= 3 

謝謝。

+0

嘗試將Table_1.Phone IN ....替換爲Table_1.Phone = Table_3.Phone上的另一個連接 –

回答

2

試試這個:

編輯:

你真的需要GROUP BY Table_1.Phone, Table_2.MasterServiceID

DECLARE @nvarcharCampaignIDTemp NVARCHAR(50); 
SET @nvarcharCampaignIDTemp = Cast(@intCampaignIDTemp AS NVARCHAR(50)); 

SELECT 
    Table1.Phone 
FROM 
    Table_1 
    INNER JOIN Table_2 
     ON Table_1.SubscriptionID = Table_2.SubscriptionID 
    INNER JOIN Table_3 
     ON Table1.Phone = Table_3.Phone 
WHERE 
    Table_1.MsgType = 'coupon' 
    AND Table_2.MasterServiceID = 121 
    AND CampaignID <> @nvarcharCampaignIDTemp 
    AND Table_3.DeliveryStatus <> 0 
    AND Count(DISTINCT Table_1.T1ID) >= 3