选择不在另一个表中的行,SQL Server查询

时间:2011-11-17 10:23:02

标签: sql sql-server-2008

主题表

CREATE TABLE [dbo].[BS_Subject](
     [SubjectID] [bigint] IDENTITY(1,1) NOT NULL,
     [DepartmentID] [bigint] NOT NULL,
     [SubjectName] [varchar](50) NOT NULL,
     [SubjectDescription] [varchar](100) NULL,
     [SubjectShortCode] [varchar](10) NOT NULL,
CONSTRAINT [PK_Subject] PRIMARY KEY CLUSTERED 
(
    [SubjectID] ASC
)

SubjectToClass表

CREATE TABLE [dbo].[BS_SubjectToClass](
[SubjectToClassID] [bigint] IDENTITY(1,1) NOT NULL,
[SubjectID] [bigint] NOT NULL,
[ClassID] [bigint] NOT NULL,
CONSTRAINT [PK_BS_SubjectToClass] PRIMARY KEY CLUSTERED 
(
[SubjectToClassID] ASC
)

我需要列出Subject表中subjectid不在指定类的SubjectToClass表中的所有行。

我有这个,但无法继续下去

select Distinct(BS_Subject.SubjectID) DepartmentID, 
       SubjectName, SubjectDescription,    SubjectShortCode
from dbo.BS_Subject
where BS_Subject.SubjectID <> (
SELECT     Distinct(BS_Subject.SubjectID)
FROM         dbo.BS_Subject, dbo.BS_SubjectToClass
Where      BS_Subject.SubjectID = BS_SubjectToClass.SubjectID
And BS_SubjectToClass.ClassID = 2)

2 个答案:

答案 0 :(得分:35)

SELECT SubjectID, DepartmentID, SubjectName, SubjectDescription, SubjectShortCode
FROM BS_Subject 
WHERE NOT EXISTS 
(SELECT SubjectToClassID FROM BS_SubjectToClass WHERE 
BS_Subject.SubjectID = BS_SubjectToClass.SubjectID
AND BS_SubjectToClass.ClassID =2)

答案 1 :(得分:11)

您需要使用NOT IN运算符 - 而不是<>(那是VB或其他......)

SELECT 
   DISTINCT(BS_Subject.SubjectID) DepartmentID, 
   SubjectName, SubjectDescription, SubjectShortCode
FROM dbo.BS_Subject
WHERE 
    BS_Subject.SubjectID NOT IN
       (SELECT DISTINCT(BS_Subject.SubjectID)
        FROM dbo.BS_Subject, dbo.BS_SubjectToClass
        WHERE BS_Subject.SubjectID = BS_SubjectToClass.SubjectID
        AND BS_SubjectToClass.ClassID = 2)