SQL中 IN 与 EXISTS的使用
大家在谈到sql优化时,都会说到用EXISTS 代替 IN 查询。
现在就谈谈这两个的用法。
IN查询相当于多个or条件的叠加,这个比较好理解,比如下面的查询
select * from user where userId in (1, 2, 3);
等效于
select * from user where userId = 1 or userId = 2 or userId = 3;
NOT IN 也很好理解,就是多个and != 条件
exists对外表用loop逐条查询,每次查询都会查看exists的条件语句,当 exists里的条件语句能够返回记录行时(无论记录行是的多少,只要能返回),条件就为真。
举个例子
select * from a where EXISTS(select id from a)
只要a表不为空,则全部数据都会返回,因为select id from a
作为条件,一直返回true。EXISTS 看的是 BOOL 值 而不是返回的结果集
所以两者的替换使用,必须要有这个思想。EXISTS 是判断条件是否为真, IN 后面接的是结果集
例如:
A 表:
id | name |
---|---|
1 | a |
2 | b |
3 | c |
4 | d |
5 | e |
B表:
id | uid |
---|---|
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
使用IN查询时
select * from A where id in (select uid from B)
此时会查询到 1,2,3,4
使用EXISTS查询
错误示范:
select * from A where EXISTS (select uid from B)
此时由于select uid from B
一直返回真,所以会查询到1,2,3,4,5
正确示范:
select * from A where EXISTS (select uid from B where A.id = B.uid)
当遍历到第五条时,由于条件为false,查询返回1,2,3,4