SQL NOT EXISTS not returning expected results

时间:2015-10-06 09:05:51

标签: sql-server sql-server-2008 reporting-services

Using SSRS 2008 R2

I'm having some problems working out how to look for records that are in one query and not another.

I've tried NOT EXISTS, NOT IN and LEFT JOIN.

When I try the sub query on its own it works fine, but when I join it to the first query with NOT EXISTS it returns no records (there should be around 5000 records returned).

I found this post SQL "select where not in subquery" returns no results and whilst I'm not sure I understand all of the answers (!) I did try filtering out any nulls that either query returns.

FYI it's not enough just to look for people who are in the first query where document type is not = 4 as I am doing something more complicated with additional columns I need for a table - I thought it would be easier for someone to point me in the right direction if I distilled the query down to that shown below.

Thanks, Eileen

SELECT
  TblPeople.PeopleId
  ,TblPeople.FirstName
  ,TblPeople.Surname

FROM 
TblPeople

WHERE TblPeople.PeopleId IS NOT NULL
AND NOT EXISTS 

(SELECT
  TblPeople.PeopleId 

FROM
  TblPeople
  INNER JOIN TblDocument 
    ON TblDocument.DocumentPeopleId = TblPeople.PeopleId

WHERE
  TblDocument.DocumentType = 4 
  AND TblPeople.PeopleId IS NOT NULL)

2 个答案:

答案 0 :(得分:1)

您的查询存在问题:

  1. 您没有将子查询链接到主查询
  2. 子查询中不需要TblPeople(因为您可以使用简单的where条件链接TblDocuments表)
  3. 固定查询如下所示:

    SELECT
      TblPeople.PeopleId
      ,TblPeople.FirstName
      ,TblPeople.Surname
    FROM 
      TblPeople
    WHERE
      TblPeople.PeopleId IS NOT NULL -- This is probably not necessary (assuming, PeopleId is the primary key, therefore it is NOT NULL).
      AND NOT EXISTS (
        SELECT
          1 -- does not really matter what is the column to retrieve
        FROM
          TblDocument AS D
        WHERE
          TblDocument.DocumentPeopleId = TblPeople.PeopleId
          AND TblDocument.DocumentType = 4
      )
    

    上述查询将列出所有没有DocumentType=4个文档的人。

      

    当我使用NOT EXISTS将它连接到第一个查询时,它返回no   记录(应该返回大约5000条记录)。

    这是因为主查询中的记录与子查询之间没有链接。 (有DocumentType = 4的记录,而PeopleId没有定义,所以任何一个都没问题 - > NOT EXISTS对所有记录都说FALSE。)

    从语义上讲,[NOT] EXISTS中的子查询逐行评估主查询记录集中的每条记录。

答案 1 :(得分:0)

我想你可以改变一下,除了:

      SELECT
      TblPeople.PeopleId
      ,TblPeople.FirstName
      ,TblPeople.Surname

    FROM 
    TblPeople

    WHERE TblPeople.PeopleId IS NOT NULL

    EXCEPT

    SELECT
      TblPeople.PeopleId 

    FROM
      TblPeople
      INNER JOIN TblDocument 
        ON TblDocument.DocumentPeopleId = TblPeople.PeopleId

    WHERE
      TblDocument.DocumentType = 4 
      AND TblPeople.PeopleId IS NOT NULL