--1. NULL 对 IN(NOT IN) 查询的影响
--测试数据
DECLARE @1 TABLE(col1 int)
INSERT @1 SELECT 1
UNION ALL SELECT NULL
UNION ALL SELECT 2DECLARE @2 TABLE(col1 int)
INSERT @2 SELECT 1--查询
SELECT [@1总记录数]=COUNT(*) FROM @1
--结果: 3SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 IN(SELECT col1 FROM @2)
--结果: 1SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 NOT IN(SELECT col1 FROM @2)
--结果: 1--在@2中插入一条NULL值
INSERT @2 SELECT NULL
SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 IN(SELECT col1 FROM @2)
--结果: 1SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 NOT IN(SELECT col1 FROM @2)
--结果: 0
GO
--2. 使用 EXISTS 代替IN
--测试数据
DECLARE @1 TABLE(col1 int)
INSERT @1 SELECT 1
UNION ALL SELECT NULL
UNION ALL SELECT 2DECLARE @2 TABLE(col1 int)
INSERT @2 SELECT 1
UNION ALL SELECT NULLSELECT [@1在@2表中存在的记录数]=COUNT(*)
FROM @1 a
WHERE EXISTS(SELECT * FROM @2 WHERE col1=a.col1)
--结果: 1SELECT [@1在@2表中存在的记录数]=COUNT(*)
FROM @1 a
WHERE NOT EXISTS(SELECT * FROM @2 WHERE col1=a.col1)
--结果: 2
--测试数据
DECLARE @1 TABLE(col1 int)
INSERT @1 SELECT 1
UNION ALL SELECT NULL
UNION ALL SELECT 2DECLARE @2 TABLE(col1 int)
INSERT @2 SELECT 1--查询
SELECT [@1总记录数]=COUNT(*) FROM @1
--结果: 3SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 IN(SELECT col1 FROM @2)
--结果: 1SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 NOT IN(SELECT col1 FROM @2)
--结果: 1--在@2中插入一条NULL值
INSERT @2 SELECT NULL
SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 IN(SELECT col1 FROM @2)
--结果: 1SELECT [@1在@2表中存在的记录数]=COUNT(*) FROM @1 a
WHERE col1 NOT IN(SELECT col1 FROM @2)
--结果: 0
GO
--2. 使用 EXISTS 代替IN
--测试数据
DECLARE @1 TABLE(col1 int)
INSERT @1 SELECT 1
UNION ALL SELECT NULL
UNION ALL SELECT 2DECLARE @2 TABLE(col1 int)
INSERT @2 SELECT 1
UNION ALL SELECT NULLSELECT [@1在@2表中存在的记录数]=COUNT(*)
FROM @1 a
WHERE EXISTS(SELECT * FROM @2 WHERE col1=a.col1)
--结果: 1SELECT [@1在@2表中存在的记录数]=COUNT(*)
FROM @1 a
WHERE NOT EXISTS(SELECT * FROM @2 WHERE col1=a.col1)
--结果: 2
go
create table test (a int ,b int )
insert test select 1,1
insert test select 2,2
insert test select 3,3
insert test select 99,4
insert test select null,5
select * from test where a not in (select b from test )
select * from test t where not exists(select 1 from test where a=t.b)
/*a b
----------- -----------
99 4a b
----------- -----------
99 4
NULL 5*/
select * from test t where not exists(select 2 from test where b=t.a )
select * from test t where not exists(select 1 from test where a=t.b)
if object_id('test')is not null drop table test
go
create table test (a int ,b int )
insert test select 1,1
insert test select 2,2
insert test select 3,3
insert test select 99,4
insert test select null,5select * from test where b not in(select a from test where b in (select a from test ))
/*
a b
99 4
NULL 5
*/