---
title: "in and exists"
author: "xshdch"
date: "2016-12-02T11:18:28Z"
tags: []
categories: ["数据库"]
slug: "in-and-exists"
draft: false
lastmod: "2016-12-02T11:18:28Z"
id: 2342448
url: "https://xshdch.iteye.com/blog/2342448"
---

http://www.jianshu.com/p/39dcef831ba2

1、in和exists
in是把外表和内表作hash连接，而exists是对外表作loop循环，每次loop循环再对内表进行查询。如果查询的两个表大小相当，那么用in和exists差别不大；如果两个表中一个较小一个较大，则子查询表大的用exists，子查询表小的用in；

尽管通常不建议在sql语句中使用*， 但在exists子查询中* 可以放心使用。exists只关心行是否存在，而不会去取各列的值。

例如：表A(小表)，表B(大表)

select * from A where cc in(select cc from B)
效率低，用到了A表上cc列的索引；

select * from A where exists(select cc from B where cc=A.cc)
效率高，用到了B表上cc列的索引。

相反的：

select * from B where cc in(select cc from A)
效率高，用到了B表上cc列的索引

select * from B where exists(select cc from A where cc=B.cc)　
效率低，用到了A表上cc列的索引。

2、not in 和not exists
not in 逻辑上不完全等同于not exists。
当输入列表中包含null值时，not exists 和not in之间的差异就表现出来了。输入列表中包含null，not in 总会返回false 和 unknown。即，null in （‘a’，‘b’，null）返回null， ‘c’ not in （‘a’，‘b’，null）的返回值是null，所以用not in之前要先过滤掉null值。而对于not exists，总是返回true 和 false。

文／GALAXY_ZMY（简书作者）
原文链接：http://www.jianshu.com/p/39dcef831ba2
著作权归作者所有，转载请联系作者获得授权，并标注“简书作者”。