将查询从NOT IN更改为NOt EXISTS

时间:2016-02-11 17:42:05

标签: mysql vba

我对vba编程有点新鲜。我有这个代码我写的现在变慢了。我刚刚从后端表移动到SQL表。我正在使用的查询,使用NOT IN。我在某些地方读过使用NOT EXISTS可能会加快速度。这是我的代码。我需要将其转换为NOT EXISTS,但我不确定如何:

SELECT BatchID
FROM TblBatchInfo
WHERE (IsNull([RSOutDateTime])=False) 
     AND (IsNull([HBDropDateTime])=False)
     AND (Format([BatchDateTime],"Short Date")=Format(Now(),"Short Date"))
     AND (IsNull(PSPassedOut=True) OR (PSPassedOut=""))
     AND LEN(LabelID)=9 
     AND [Area] <> 5
     AND [Area] <> 6
     AND [Area] <> 7
     AND (BatchID Not In (SELECT [BatchID]
                                          FROM [TblBatchInfo]
                                          WHERE (IsNull([RSOutDateTime]) = True)
                                           AND LEN(LabelID)=9
                                           AND [Area] <> 5 
                                           AND [Area] <> 6
                                           AND [Area] <> 7
                                           AND (Format([BatchDateTime], "Short Date") = Format(Now(), "Short Date"))))
GROUP BY BatchID
ORDER BY BatchID;

1 个答案:

答案 0 :(得分:1)

使用表别名,因为在子查询中,您将引用两个表。您也可以执行NOT IN (5,6,7)而不是多个<>

SELECT BatchID
FROM TblBatchInfo x
WHERE (IsNull([RSOutDateTime])=False) 
     AND (IsNull([HBDropDateTime])=False)
     AND (Format([BatchDateTime],"Short Date")=Format(Now(),"Short Date"))
     AND (IsNull(PSPassedOut=True) OR (PSPassedOut=""))
     AND LEN(LabelID)=9 
     AND [Area] NOT IN (5,6,7)
     AND NOT EXISTS (SELECT 1 [BatchID]
                     FROM [TblBatchInfo] y
                     WHERE (IsNull([RSOutDateTime]) = True)
                         AND x.[BatchId] = y.BatchID
                         AND LEN(LabelID)=9
                         AND [Area] NOT IN (5,6,7) 
                         AND (Format([BatchDateTime], "Short Date") = Format(Now(), "Short Date"))
                    )
GROUP BY BatchID
ORDER BY BatchID;