SQL返回记录NOT IN子查询

时间:2015-06-16 12:51:08

标签: ms-access

我正在尝试返回所有不在

中的记录
Select UID FROM EnrollmentsTbl WHERE (UID Is Not Null)

当前SQL语句返回链接表UsersDataTblUsersDataCareerTbl

中的所有记录

根据我的研究,使用索引字段UID将无法生成我想要的结果,当我使用其他字段UserName时,会呈现所需的结果:

是否有办法让我在子查询中使用索引字段?

以下内容返回链接表中的所有记录,但不排除子查询记录:

<asp:AccessDataSource ID="AccessDataSource2" runat="server" 

     DataFile="<%$ ConnectionStrings:AccessSubSiteString %>" 
     SelectCommand="SELECT UsersDataTbl.StudentID, 
                           UsersDataTbl.LastName, UsersDataTbl.FirstName, 
                           UsersDataTbl.UID, UsersDataCareerTbl.Battallion, 
                           UsersDataCareerTbl.Station, UsersDataCareerTbl.Shift
                     FROM UsersDataTbl 
                     LEFT JOIN UsersDataCareerTbl ON UsersDataTbl.UID = UsersDataCareerTbl.UID
                     WHERE (((UsersDataTbl.Career) = True) 
                       AND ((UsersDataTbl.Active) = True) 
                       AND ((UsersDataTbl.UID) NOT IN 
                            (SELECT UID FROM EnrollmentsTbl 
                             WHERE (UID IS NOT NULL)))) 
                     ORDER BY UsersDataTbl.LastName, UsersDataTbl.FirstName">
</asp:AccessDataSource>

以下内容返回所需的结果(但UserName不是所需或可靠的字段):

<asp:AccessDataSource ID="AccessDataSource2" runat="server" 
DataFile="<%$ ConnectionStrings:AccessSubSiteString %>" 
SelectCommand="SELECT UsersDataTbl.StudentID, UsersDataTbl.LastName, UsersDataTbl.FirstName, 
UsersDataTbl.UID, UsersDataCareerTbl.Battallion, UsersDataCareerTbl.Station, UsersDataCareerTbl.Shift
FROM UsersDataTbl LEFT JOIN UsersDataCareerTbl ON UsersDataTbl.UID = UsersDataCareerTbl.UID
WHERE (((UsersDataTbl.Career)=True) AND ((UsersDataTbl.Active)=True) AND ((UsersDataTbl.UID) 
Not In (Select UserName FROM EnrollmentsTbl WHERE (UserName Is Not Null)))) 
ORDER BY UsersDataTbl.LastName, UsersDataTbl.FirstName">
</asp:AccessDataSource>

1 个答案:

答案 0 :(得分:1)

您可以在UID上将EnrollmentsTbl连接到UsersDataTbl,然后将And EnrollmentsTbl.UID Is Null添加到WHERE子句中。

或者,您可以使用NOT EXISTS子句,但我认为Access数据库的性能较差:

 WHERE NOT EXISTS (SELECT NULL FROM EnrollmentsTbl et WHERE et.UID = UsersDataTbl.UID)