简单查询出错了

时间:2018-02-18 17:08:29

标签: sql-server tsql

我必须休息一天。这应该是显而易见的,但我不明白。

-- check for necessary updates to dbnotes
select count(distinct table_name) 
from ccsv4.[INFORMATION_SCHEMA].[COLUMNS]

返回46

select count(distinct table_name) 
from dbnotes

返回44

select distinct table_name 
from ccsv4.[INFORMATION_SCHEMA].[COLUMNS]
where table_name not in (select distinct table_name from dbnotes)
order by table_name

什么都不返回

select distinct table_name 
from dbnotes
where  table_name not in (select distinct table_name 
                          from ccsv4.[INFORMATION_SCHEMA].[COLUMNS])
order by table_name

什么都不返回

我想念的是什么人?

1 个答案:

答案 0 :(得分:1)

您正在使用not in。如果子查询中的任何值为NULL,则不会返回任何内容。

使用子查询,总是使用not exists。它具有正确的语义:

select distinct table_name
from ccsv4.[INFORMATION_SCHEMA].[COLUMNS] c
where not exists (select 1
                  from dbnotes d
                  where d.table_name = c.table_name 
                 );

我非常确定表格必须至少包含一列,因此您也可以使用information_schema.tables。它为您节省了distinct

select table_name
from ccsv4.information_schema.tables t
where not exists (select 1
                  from dbnotes d
                  where d.table_name = t.table_name 
                 );
相关问题