Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows not in another table, SQL Server query

Subject table

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 table

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 ) 

I need list all the rows in the Subject table where subjectid is not in SubjectToClass table of a specified class.

I have this but unable to go any further

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) 
like image 705
Taufiq Abdur Rahman Avatar asked Nov 17 '11 10:11

Taufiq Abdur Rahman


People also ask

How do I SELECT data from one table is not in another table?

We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

How do you get not matching records from two tables in SQL?

SELECT B. Accountid FROM TableB AS B LEFT JOIN TableA AS A ON A.ID = B. Accountid WHERE A.ID IS NULL; LEFT JOIN means it takes all the rows from the first table - if there are no matches on the first join condition, the result table columns for table B will be null - that's why it works.


2 Answers

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) 
like image 53
shahkalpesh Avatar answered Sep 23 '22 05:09

shahkalpesh


You need to use the NOT IN operator - not the <> (that's VB or something....)

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) 
like image 37
marc_s Avatar answered Sep 19 '22 05:09

marc_s