Not In access query

泄露秘密 提交于 2020-01-15 13:34:13

问题


I have two tables below

tblLoc(LocCode) tblData(Item,LocCode)

In tblData, there is 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?


回答1:


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;



回答2:


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'?



来源:https://stackoverflow.com/questions/7345074/not-in-access-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!