WHERE <表达式> <操作符> (子查询)
in | exists |
当表达式与子查询返回的结果集中的某个值相等时,返回 TRUE,否则返回 FALSE; | 用于判断子查询的结果集是否为空,若子查询的结果集不为空,返回 TRUE,否则返回 FALSE; |
适合外表大而内表小的情况 | 适合内表大而外表小的情况 |
无论哪个表大,用 not exists 都比 not in 速度快 | |
1、A是表达式,B是子查询结果集 2、若A在B里面,则返回True |
|
方便理解,画个图 |
select * from emp where dept_id = (select id from dept where name = "销售部")
select * from emp where dept_id <> (select id from dept where name = "销售部")
select * from emp where dept_id in (select id from dept where name = "财务部" or name ="销售部")
select id from dept where name = "财务部" or name ="销售部"
select * from emp where dept_id in (1,3)
select * from emp where dept_id not in (select id from dept where name = "财务部" or name ="销售部")
其实就是上面栗子结果集的取反
select * from emp where exists(select * from dept where id = 1)
select * from dept where id = 1
可以看到,查询结果集不为空,所以 exists() 返回 true
select * from emp where true
select * from emp where exists (select * from dept where id = 1) and dept_id = 2