---
title: "浅说：in、not in、exists和not exists的区别"
author: "danielhjd"
date: "2011-05-29T15:08:20Z"
tags: ["SQL"]
categories: ["数据库"]
slug: "in-not-in-exists-not-exists"
draft: false
lastmod: "2011-05-29T15:08:20Z"
id: 1063492
url: "https://danielhjd.iteye.com/blog/1063492"
---

**in、not in、exists和not exists的区别：**

 

in和exists的区别：

**exists:**存在，后面一般都是子查询，当子查询返回**行数**时，exists返回true。

```
select * from class where exists (select'x"form stu where stu.cid=class.cid)
```

   
当in和exists在查询效率上比较时，in查询的效率快于exists的查询效率

exists(xxxxx)后面的子查询被称做相关子查询, 他是不返回列表的值的.  
只是返回一个ture或false的结果(这也是为什么子查询里是select 'x'的原因 当然也可以

select任何东西) 也就是它只在乎括号里的数据能不能查找出来，是否存在这样的记录。  
其运行方式是先运行主查询一次 再去子查询里查询与其对应的结果 如果存在，返回ture则输

出,反之返回false则不输出,再根据主查询中的每一行去子查询里去查询.

 

执行顺序如下：  
1.首先执行一次外部查询

```
select * from class 
```

   
2.对于外部查询中的每一行分别执行一次子查询，而且每次执行子查询时都会引用外部查询中当

前行的值。  
3.使用子查询的结果来确定外部查询的结果集。

如果外部查询返回100行，SQL 就将执行101次查询，一次执行外部查询，然后为外部查询返回

的每一行执行一次子查询。

 

**in：包含**

查询和所有女生年龄相同的男生

```
select * from stu where sex='男' and age in(select age from stu where sex='女')
```

   
in()后面的子查询 是返回结果集的,换句话说执行次序和exists()不一样.子查询先产生结果集,  
然后主查询再去结果集里去找符合要求的字段列表去.符合要求的输出,反之则不输出.

not in和not exists的区别：  
not in 只有当子查询中，select 关键字后的字段有**not null约束或者有这种暗示时用**not in,另外如果*主查询中表大*，子查询中的表小但是记录多，则应当使用not in,  
例如:查询那些班级中没有学生的，

```
select * from class where cid not in(select distinct cid from stu)
```

   
当表中cid存在null值，**not in 不对空值进行处理**  
解决:

```
select * from class where cid not in (select distinct cid from stu where cid is not null)

```

   
not in的执行顺序是：

是在表中一条记录一条记录的查询(查询每条记录）符合要求的就返回结果集，不符合的就继续查询下一条记录，直到把表中的记录查询完。也就是说为了证明找不到，所以只能查询全部记录才能证明。并没有用到索引。

not exists：如果主查询表中记录少，子查询表中记录多，并有索引。  
例如:查询那些班级中没有学生的，

```
select * from class2 where not exists (select * from stu1 where stu1.cid =class2.cid)
```

 

not exists的执行顺序是：在表中查询，是根据索引查询的，如果存在就返回true，如果不存在就返回false，不会每条记录都去查询。  
之所以要多用not exists，而不用not in，也就是not exists查询的效率远远高与not in查询的效率。