SQL Server中这两个SQL查询的区别,

SQL Server中这两个SQL查询的区别,,sql,sql-server,except,Sql,Sql Server,Except,我正在努力寻找那些没有支付任何费用的身份证 存在一些重复ID,其中一些记录的feepay值不为null,一些记录的feepay值为null 为什么这两个查询返回不同的输出 select distinct ID from MyTable where FeePaid is null and ID not in (select distinct ID from MyTable where FeePaid is not null) 及 第二个应该做你想做

我正在努力寻找那些没有支付任何费用的身份证

存在一些重复ID,其中一些记录的feepay值不为null,一些记录的feepay值为null

为什么这两个查询返回不同的输出

select distinct ID 
from MyTable 
where FeePaid is null  
  and ID not in (select distinct ID from MyTable 
                 where FeePaid is not null)


第二个应该做你想做的。我还可以建议:

select id
from mytable
group by id
having max(feepaid) is null;
第一个查询将
not in
与子查询一起使用,我强烈反对这样做。一种可能性是
id
NULL
。如果它曾经是
NULL
,则
不在
条件返回
NULL
,并且查询不返回任何行

要执行您想要的操作,我建议使用
notexists

select distinct t.ID
from MyTable t
where FeePaid is null and
      not exists (select 1
                  from MyTable t2
                  where t2.id = t.id and t2.FeePaid is not null
                 );
select distinct t.ID
from MyTable t
where FeePaid is null and
      not exists (select 1
                  from MyTable t2
                  where t2.id = t.id and t2.FeePaid is not null
                 );