2011-05-25 150 views
-1

的MS SQL Server 2008優化這個查詢

enter image description here

SELECT Action.* 
FROM Mailing 
     INNER JOIN ActionCategoryMailingBunch 
     ON Mailing.MailingID = ActionCategoryMailingBunch.MailingID 
     INNER JOIN ActionCategory 
     ON ActionCategoryMailingBunch.ActionCategoryID = 
      ActionCategory.ActionCategoryID 
     INNER JOIN Action 
     ON ActionCategory.ActionCategoryID = Action.ActionCategoryID 
WHERE (Mailing.MailingID = 7) 
     AND (Mailing.MailingID NOT IN (SELECT MailingID 
             FROM MailingReport)) 
     AND (Action.ActionID NOT IN (SELECT ActionID 
            FROM MailingReport)) 
     AND (ActionCategoryMailingBunch.MailingBunchStatusID = 4) 

尤其是該塊

(Mailing.MailingID NOT IN (SELECT MailingID FROM MailingReport)) 
AND (Action.ActionID NOT IN (SELECT ActionID FROM MailingReport)) 
+2

如果這就是您需要的語義,然後不知道你期望我們處理您的查詢!如果您遇到性能問題,請發佈執行計劃並定義包括索引在內的所有相關表格。雖然由於您只是從Action中選擇列,您可能想使用EXISTS而不是JOIN – 2011-05-25 09:23:56

回答

2

添加下面的代碼在SELECT語句

Left Join MailingReport MR on MR.ActionID = Mailing.MailingID 

添加以下代碼Where子句

(MR.ActionID is null) 

性能提升是由於以下塊

(Mailing.MailingID NOT IN (SELECT MailingID FROM MailingReport)) 

最終查詢

SELECT Action.* 
FROM Mailing 
     INNER JOIN ActionCategoryMailingBunch 
     ON Mailing.MailingID = ActionCategoryMailingBunch.MailingID 
     INNER JOIN ActionCategory 
     ON ActionCategoryMailingBunch.ActionCategoryID = 
      ActionCategory.ActionCategoryID 
     INNER JOIN Action 
     ON ActionCategory.ActionCategoryID = Action.ActionCategoryID 
     Left Join MailingReport MR on MR.ActionID = Mailing.MailingID 
WHERE (Mailing.MailingID = 7) 
     --AND (Mailing.MailingID NOT IN (SELECT MailingID 
     --        FROM MailingReport)) 
     AND 
     (MR.ActionID is null) 
     AND (Action.ActionID NOT IN (SELECT ActionID 
            FROM MailingReport)) 
     AND (ActionCategoryMailingBunch.MailingBunchStatusID = 4) 

同樣可以爲第二塊 性能做由於第二塊

AND (Action.ActionID NOT IN (SELECT ActionID FROM MailingReport)) 

最終查詢這兩個塊

SELECT Action.* 
FROM Mailing 
     INNER JOIN ActionCategoryMailingBunch 
     ON Mailing.MailingID = ActionCategoryMailingBunch.MailingID 
     INNER JOIN ActionCategory 
     ON ActionCategoryMailingBunch.ActionCategoryID = 
      ActionCategory.ActionCategoryID 
     INNER JOIN Action 
     ON ActionCategory.ActionCategoryID = Action.ActionCategoryID 
     Left Join MailingReport MR on MR.ActionID = Mailing.MailingID 
     Left Join MailingReport MRA on MRA.ActionID = Action.ActionID 
WHERE (Mailing.MailingID = 7) 
     AND 
     (MR.ActionID is null) 
     AND 
     (MRA.ActionID is null) 
     AND (ActionCategoryMailingBunch.MailingBunchStatusID = 4) 
+0

[將NOT IN轉換爲LEFT JOIN/IS NULL不是優化](http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server /) – 2011-05-25 11:35:09

+0

在過去,我有類似的問題與我的查詢。以上是解決問題的糾正措施。據我所知,In查詢在內部充當了一個循環,我在這裏避開它。 – Pankaj 2011-05-25 11:37:01

+0

這是我過去的經歷。 – Pankaj 2011-05-25 11:47:25