在一个表中查找不在另一个表中的行 - SQL Server查询

时间:2015-05-29 07:46:51

标签: sql-server

请告诉我为什么这不起作用:

SELECT t1.id
FROM table1 t1
where t1.id not in
(select t2.id
from table2 t2
where t2.somedate between '2015-01-01 00:00:00' and '2015-04-30 23:59:59'
)
group by t1.id

子查询正常工作,第一个选择工作,但是当我运行整个事情时,它会出现空白。

我试图在一个表中找到不在另一个表中的记录(ID)。

非常感谢任何帮助。 这是在SQL Server btw。

由于

3 个答案:

答案 0 :(得分:1)

您可以使用左连接

SELECT t1.id
FROM table1 t1
Left Join table2 t2 on T2.Id=t1.id and
t2.somedate between '2015-01-01 00:00:00' and '2015-04-30 23:59:59'
where t2.id is null  group by t1.id

其他选项是使用存在

select
    t1.id
from
    table1 t1
where
    not exists
    (select 1 from table2 t2 where t1.id = t2.id and 
     t2.somedate between '2015-01-01 00:00:00' and '2015-04-30 23:59:59'
    and t2.id is null  group by t1.id)

答案 1 :(得分:0)

使用左连接

SELECT t1.id
FROM table1 t1
Left Join table2 t2 on T2.Id=t1.id and
t2.somedate between '2015-01-01 00:00:00' and '2015-04-30 23:59:59'
where t2.id is null
group by t1.0

或您的查询已更新

SELECT t1.id
FROM table1 t1
where isnull(t1.id,-1) not in
(select isnull(t2.id,-1)
from table2 t2
where t2.somedate between '2015-01-01 00:00:00' and '2015-04-30 23:59:59'
)
group by t1.id

答案 2 :(得分:0)

您的table2可能包含NULL个ID结果,因此NOT IN未按预期执行。

参考 https://stackoverflow.com/a/3925698/1287352