这两个sql查询返回相同的结果吗?

时间:2011-09-16 07:09:20

标签: sql

select c1, c2 from t1
where not exists
(
select 1 from t2
where t1.c2 = t2.c3
)

select c1, c2 from t1
where c2 not in 
(
select c3 from t2
)

1 个答案:

答案 0 :(得分:5)

不,他们不一样。不同之处在于如何处理NULL值。

  • not exists会返回c2等于NULL
  • 的记录
  • not in 会返回c2等于NULL
  • 的记录

测试脚本

DECLARE @t1 TABLE (c1 INTEGER, c2 INTEGER)
DECLARE @t2 TABLE (c3 INTEGER)

INSERT INTO @t1 VALUES (NULL, NULL), (1, NULL), (NULL, 1), (1, 1)
INSERT INTO @t2 VALUES (NULL), (1)


select c1, c2 from @t1 t1
where not exists
(
  select 1 from @t2 t2
  where t1.c2 = t2.c3
) -- returns (NULL, NULL) & (1, NULL)


select c1, c2 from @t1
where c2 not in 
(
  select c3 from @t2
) -- returns nothing