SQL Select omitting results from a sub-query

67 Views Asked by At

I have the following code which, when run separately, produces the results I expect but when run collectively returns nothing:

SELECT SurveyUID FROM   tbSurvey AS tbS
WHERE  NOT EXISTS   
(SELECT tbS.SurveyUID
FROM         tbSurvey AS tbS INNER JOIN
                  tbSurveyElementCategory AS tbSEC ON tbS.SurveyUID = tbSEC.SurveyUID INNER JOIN
                  tbElementCategory AS tbEC ON tbSEC.ElementCategoryID = tbEC.ElementCategoryID
WHERE     (tbEC.ElementCategoryID = 75))

The first line returns 185 records and the sub-query returns 20 records as a sub-set of the first query. I am trying to return the 165 records that don't appear in the sub-query. Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

You forgot put tbS.SurveyUID = tbS1.SurveyUID condition

Try this:

SELECT SurveyUID 
FROM   tbSurvey AS tbS
WHERE NOT EXISTS (SELECT tbS1.SurveyUID
                  FROM tbSurvey AS tbS1 
                  INNER JOIN tbSurveyElementCategory AS tbSEC ON tbS1.SurveyUID = tbSEC.SurveyUID 
                  INNER JOIN tbElementCategory AS tbEC ON tbSEC.ElementCategoryID = tbEC.ElementCategoryID
                  WHERE (tbEC.ElementCategoryID = 75) AND tbS.SurveyUID = tbS1.SurveyUID
                 )
0
On

Your query is wrong. You have to write: ...WHERE SurveyUID NOT IN (...subquery...). In your query you say "give me all ID-s if the subquery has no results" but it has results.