【问题标题】:Difference in these two SQL queries in SQL Server,SQL Server 中这两个 SQL 查询的区别,
【发布时间】:2021-02-25 09:49:51
【问题描述】:

我正在寻找那些没有支付任何费用的 ID。

有一些重复的 ID,其中一些记录的 FeePaid 不为空,一些记录的 FeePaid 为空。

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

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

select distinct ID 
from myTable 
where FeePaid is null  

except

select distinct ID 
from MyTable 
where FeePaid is not null

【问题讨论】:

    标签: sql sql-server except


    【解决方案1】:

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

    select id
    from mytable
    group by id
    having max(feepaid) is null;
    

    第一个查询使用带有子查询的not in,我强烈反对。一种可能性是idNULL。如果是曾经NULL,那么not in 条件返回NULL,并且查询不返回任何行。

    要做你想做的,我建议使用not exists

    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
                     );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 2017-01-30
      • 2012-04-19
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      相关资源
      最近更新 更多