查询条件为空值

时间:2018-10-11 19:37:54

标签: sql-server tsql sql-server-2014

我正在尝试使用not in和exist比较空值,但是发现了一些区别 为什么最新查询返回null?它与db参数有关吗?

--SET ANSI_NULLS On

CREATE TABLE #Tmp (id INT)
CREATE TABLE #Tmp1 (id INT)

INSERT INTO #Tmp(id) VALUES (1)
INSERT INTO #Tmp(id) VALUES (null)


INSERT INTO #Tmp1(id) VALUES (1)
INSERT INTO #Tmp1(id) VALUES (null)

SELECT id FROM #Tmp WHERE id IN (SELECT id FROM #tmp1)

SELECT id FROM #Tmp WHERE EXISTS(SELECT 1 FROM #Tmp1 WHERE #Tmp1.id = #Tmp.id)

SELECT id FROM #Tmp WHERE id NOT IN (SELECT id FROM #tmp1)

SELECT id FROM #Tmp WHERE NOT EXISTS(SELECT 1 FROM #Tmp1 WHERE #Tmp1.id = #Tmp.id)

DROP TABLE #Tmp
DROP TABLE #Tmp1 

2 个答案:

答案 0 :(得分:1)

在SQL Server中,请记住NULL不会对任何东西返回TRUE的相等性检查(除非您正在使用ANSI_NULLS):

SELECT 1 
WHERE 1=NULL

SELECT 1
WHERE NULL = NULL

仅在使用IS / IS NOT时返回True

SELECT 1
WHERE NULL IS NULL

对于您的最后一个查询,满足WHERE子句中该要求的唯一记录是您的NULL行。等效为:

SELECT id FROM #Tmp 
WHERE id IS NULL

要解决您的问题,请在此处添加第二个子句:

SELECT id FROM #Tmp 
WHERE NOT EXISTS(
SELECT 1 
FROM #Tmp1 
WHERE #Tmp1.id = #Tmp.id OR #Tmp.id IS NULL
)

答案 1 :(得分:0)

这很简单:

id IN (1, NULL)
<=>
id = 1 OR id = NULL

还有negation of alternative

id NOT IN (1, NULL)
<=>
id != 1 AND id != NULL -- yields NULL

摘要:

如果您想使用NOT IN,请确保您的列表中不包含NULL

SELECT id FROM #Tmp WHERE id NOT IN (SELECT id FROM #tmp1 WHERE id IS NOT NULL)

SELECT id FROM #Tmp WHERE id NOT IN (SELECT COALESCE(id,-1) FROM #tmp1)