开发者

Not In access query

I have two tables below

tblLoc(LocCode) tblData(Item,LocCode)

In tblData, there is开发者_如何学Python extra LocCode that does not find in tblLoc.

SELECT D.LocCode
FROM tblData AS D
WHERE D.LocCode NOT IN (SELECT LocCode FROM tblLoc);

I use this query. It's slow. Is there any better query?


Use a LEFT JOIN on LocCode between tblData and tblLoc. Restrict the result set to only those rows where tblLoc LocCode is Null. Add an index on LocCode for tblLoc, if you don't already have one.

SELECT d.LocCode
FROM
    tblData AS d
    LEFT JOIN tblLoc AS l
    ON d.LocCode = l.LocCode
WHERE l.LocCode Is Null;


The relational operator you refer to is known as semi difference or anti join. There are arious way of writing an anti join in Access (ACE, Jet, whatever): in addition to yours and @HansUp's, here are a couple more:

SELECT D.LocCode
  FROM tblData AS D
 WHERE D.LocCode <> ALL (SELECT LocCode FROM tblLoc);

 SELECT D.LocCode
  FROM tblData AS D
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM tblLoc
                    WHERE D.LocCode = L.LocCode
                  );

I think the latter is better because the parameters to the preciate are proximate in the code and therefore easier for me as a human to read and understand.

HansUp considers theirs to be better because it should be faster than yours (but they would probably join me in urging you to always test using data typical to your use case).

How do you define 'better'?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜