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

Ani*_*nil 1 sql

select c1, c2 from t1
where not exists
(
select 1 from t2
where t1.c2 = t2.c3
)
Run Code Online (Sandbox Code Playgroud)

select c1, c2 from t1
where c2 not in 
(
select c3 from t2
)
Run Code Online (Sandbox Code Playgroud)

Lie*_*ers 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
Run Code Online (Sandbox Code Playgroud)