通过排除另一个查询的结果来构建查询

时间:2011-12-12 20:39:08

标签: sql ms-access

我正在Access 2010中设计一个数据库。

我的查询可以按照我的要求运行:

    SELECT Participants.ParticipantID, [FirstName]+' '+[LastName] AS Participant
    FROM Participants
    WHERE (((Participants.SiteName)=forms!DailyWorkshops!SiteName) And 
((Participants.YearLookup)=forms!DailyWorkshops!YearLookup))
    ORDER BY Participants.FirstName, Participants.LastName;

现在我想要另一个查询给我其他所有内容。

    SELECT Participants.ParticipantID, [FirstName]+' '+[LastName] AS Participant
    FROM Participants

    WHERE 

    **exclude all these results 
    (((Participants.SiteName)=forms!DailyWorkshops!SiteName) And
 ((Participants.YearLookup)=forms!DailyWorkshops!YearLookup))**


    ORDER BY Participants.FirstName, Participants.LastName;

这似乎有效,但我想知道,这是最简单的方法吗?

    SELECT Participants.ParticipantID, [FirstName]+' '+[LastName] AS Participant
    FROM Participants
    WHERE Participants.ParticipantID NOT IN 

    (SELECT Participants.ParticipantID FROM Participants WHERE 
     (((Participants.SiteName)=forms!DailyWorkshops!SiteName) And 
((Participants.YearLookup)=forms!DailyWorkshops!YearLookup)))
    ORDER BY Participants.FirstName, Participants.LastName;

2 个答案:

答案 0 :(得分:1)

为什么这不是很简单......

SELECT Participants.ParticipantID, [FirstName]+' '+[LastName] AS Participant
FROM Participants
WHERE 
    NOT 
       (((Participants.SiteName)=forms!DailyWorkshops!SiteName) And
        ((Participants.YearLookup)=forms!DailyWorkshops!YearLookup))
ORDER BY Participants.FirstName, Participants.LastName;

唯一的原因可能是因为列中的空值,您可以修复:

SELECT Participants.ParticipantID, [FirstName]+' '+[LastName] AS Participant
FROM Participants
WHERE 
    NOT 
       (((Participants.SiteName)=forms!DailyWorkshops!SiteName OR
             IsNull(Participants.SiteName)) And
        ((Participants.YearLookup)=forms!DailyWorkshops!YearLookup OR
             IsNull(Participants.YearLookup)))
ORDER BY Participants.FirstName, Participants.LastName;

答案 1 :(得分:1)

我一般认为这种形式:

SELECT field
from list_a
where field not in (select field from list_b)  

将采用以下形式:

SELECT a.field
from list_a a left join (select field from list_b) b on a.field=b.field
where b.field is NULL 

我认为JOIN比NOT IN更快。

编辑:更改为在选择而不是表格上显示联接。

编辑:我不明白为什么这个答案被投了票。