SQL查询SELECT IN和SELECT NOT IN

时间:2012-11-09 00:01:48

标签: sql sql-server

有谁知道为什么以下2个查询的结果不能与第3个查询的结果相加?

SELECT COUNT(leadID) FROM leads 
WHERE makeID NOT IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 1)
AND modelID NOT IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 2)

SELECT COUNT(leadID) FROM Leads 
WHERE makeID IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 1)
OR modelID IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 2)

SELECT COUNT(leadID) FROM Leads

第一个查询是我需要的计数。第二个是告诉用户根据DG_App.dbo.uploadData表的内容抑制了多少记录。第三个查询只是所有记录的直接计数。

当我运行这些查询1的结果时,查询2的结果会出现大约46K记录,小于整个表的计数。我曾经使用()对WHERE语句进行分组,但这根本没有改变计数。

这是MSSQL Server 2012。

对此的任何输入都会很棒。

由于

2 个答案:

答案 0 :(得分:4)

你有任何NULL值吗?它们不会出现在第一次的第一次,我认为你错过了那些。

SELECT Count(leadID) FROM Leads WHERE makeID is Null or modelID is null

编辑:我必须添加一些注意事项:因为有一个AND和OR条件,事情会变得复杂一点!

  • Null IN()始终评估为 Null ,不会显示行
  • Null NOT IN()始终评估为 Null ,不会显示行
  • Null AND Something 评估为 Null False ,行不会显示
  • Null OR Something 评估为 True 如果Something True ,则评估为 Null ,仅评估为 Null 将出现一些行

这意味着在前两个查询中,一些记录已经计入Null,而其他记录则没有。这就是你想念的:

  • 您遗漏了makeIDmodelID都为空的记录:

    SELECT Count(leadID) FROM Leads WHERE makeID is Null and modelID is null
    
  • 但是你也错过了makeID为空的记录,modelID不为空且不在第二个子查询中:

    SELECT Count(leadID) FROM Leads
    WHERE makeID is Null
    AND modelID NOT IN (...)
    
  • modelID为空且makeID不在第一个子查询中的那些:

    SELECT Count(leadID) FROM Leads
    WHERE makeID is NOT IN (...)
    AND modelID is Null
    

答案 1 :(得分:2)

我能想到的三个案例:

  • uploadDataMapID uploadID 不等于3
  • uploadDataMapID uploadRowID 不等于1或2
  • 线索表格中有 makeID modelID 条目

SELECT count(leadID) FROM leads WHERE makeID IS NULL OR modelID IS NULL

SELECT count(leadID) 
FROM leads AS l INNER JOIN DG_App.dbo.uploadData AS u ON l.makeID = u.uploadDataMapID
WHERE u.uploadID <> 3 OR u.uploadRowID <> 1

SELECT count(leadID)
FROM leads AS l INNER JOIN DG_App.dbo.uploadData AS u ON l.modelID = u.uploadDataMapID
WHERE u.uploadID <> 3 OR u.uploadRowID <> 2

这三个查询应该为您提供缺失的记录。