count
--------
999999
(1 row)
Time: 488.649 ms
test=# select count(*) from outtable big where exists (select id1 from outtable where id1>1);
count
---------
1000000
(1 row)
Time: 313.216 ms
(select id1 from outtable where id1>1) 我们知道,这个是有返回结果的,且对exists前面的count(*) 即表任一行是没有任何影响的,故相当于elect count(*) from outtable big ; 即不存在限制条件。
(select id1 from outtable where big.id1>1)我们知道,这个是有返回结果的,且exists对前面的语句是存在限制的,那就是big.id1>1 故相当于select count(*) from outtable big where big.id1>1 ;
select * from 表A where exists(select * from 表B where 表B.id=表A.id)
这句相当于
select * from 表A where id in (select id from 表B)
对于表A的每一条数据,都执行select * from 表B where 表B.id=表A.id的存在性判断,如果表B中存在表A当前行相同的id,则exists为真,该行显示,否则不显示。
tips:
1.通常NOT EXISTS要比NOT IN 要快, 因为NOT EXISTS可以使用结合算法而NOT IN 就不行了,而EXISTS则不如IN快, 因为这时候IN可能更多的使用结合算法.
2.通常exists 不走索引,而in走索引。
参考
1. http://www.cnblogs.com/a-zx/articles/1749957. html