Mysql NOT IN和NOT EXIST不一样?

new*_*bie 6 mysql

我有时互换使用NOT IN,并NOT EXIST在我的SQL查询,都产生相同的结果.背后的逻辑NOT EXIST是一样的NOT IN吗?因为我认为NOT IN......(在子查询中被评估为"OR")等于NOT EXIST(也被评估为"OR")?或者我错过了什么?

Qua*_*noi 12

您可能会对本文感兴趣:

简而言之,与子查询返回的两个句柄值的方式NOT IN略有不同.NOT EXISTSNULL

如果没有NULL值,它们都会执行一种类型NESTED LOOP ANTI JOIN,但NOT IN效率会更高一些.


Tho*_*mas 5

不,它们不一样。IN 函数转换为一系列 OR 语句。通常,当人们在 IN 函数中使用子查询并且该查询返回至少一个空值时,这会让他们感到困惑。例如Col Not In( Select Foo From Bar )。这Col <> Foo对每一行进行比较。如果 Foo 的值之一为空,您会得到Col <> NULL并且整个语句返回 false 导致没有行。

Exists 只是确定是否返回了子查询中的任何行(不存在是指不能返回任何行)。Select 子句被完全忽略。


例子:

Create Table Test ( Id int not null )
Insert Test ( 1 )
Insert Test ( 2 )
Insert Test ( 3 )

Create Table Bar  ( Foo int null )
Insert Bar ( Null )
Insert Bar ( 1 )
Insert Bar ( 2 )
Run Code Online (Sandbox Code Playgroud)

以下将导致没有行,因为我们正在有效地进行比较 Not( Id = Null Or Id = 1 Or Id = 2 )

Select Id
From Test
Where Id Not In( Select Foo From Bar )
Run Code Online (Sandbox Code Playgroud)

然而,以下将返回一行

Select Id
From Test
Where Not Exists( Select 1 From Bar Where Foo = Id )
Run Code Online (Sandbox Code Playgroud)

在上面的查询中,我将得到 Id = 3。