优化此查询

时间:2011-05-25 08:56:10

标签: sql-server-2008 query-optimization

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))

1 个答案:

答案 0 :(得分: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 )