exist语句与inner join语句的区别

一、表结构

注意两张表的id字段没有唯一约束。

postgres=# \d a
                 Table "public.a"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 id     | integer |           | not null |
 v      | text    |           |          |
​
postgres=# \d b
                 Table "public.b"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 id     | integer |           | not null |
 v      | text    |           |          |
​
postgres=#

二、两条SQL语句

-- 语句一
select a.* from a where exists(select 1 from b where a.id = b.id);
-- 语句二
select a.* from a join b on a.id = b.id ;

三、执行计划

语句一:使用Hash Semi Join链接,SEMI JOIN表示当A表中的记录,在B表上产生符合条件之后就返回,不会再继续查找B表记录了,所以如果B表有重复,也不会产生重复的多条记录。

语句二:使用Hash Join链接,JOIN表示当A表中的记录,在B表上产生符合条件之后还需要查看符合条件的有几条,如果B表有重复,那么返回的A表记录也就有重复。

postgres=# explain select a.* from a where exists(select 1 from b where a.id = b.id);
                         QUERY PLAN
-------------------------------------------------------------
 Hash Semi Join  (cost=1.04..2.11 rows=2 width=36)
   Hash Cond: (a.id = b.id)
   ->  Seq Scan on a  (cost=0.00..1.03 rows=3 width=36)
   ->  Hash  (cost=1.02..1.02 rows=2 width=4)
         ->  Seq Scan on b  (cost=0.00..1.02 rows=2 width=4)
(5 rows)
​
postgres=# explain select a.* from a join b on a.id = b.id ;
                         QUERY PLAN
-------------------------------------------------------------
 Hash Join  (cost=1.04..2.11 rows=2 width=36)
   Hash Cond: (a.id = b.id)
   ->  Seq Scan on a  (cost=0.00..1.03 rows=3 width=36)
   ->  Hash  (cost=1.02..1.02 rows=2 width=4)
         ->  Seq Scan on b  (cost=0.00..1.02 rows=2 width=4)
(5 rows)
​
postgres=#

四、实际运行

postgres=# table a;
 id | v
----+---
  1 | a
  2 | a
  3 | a
(3 rows)
​
postgres=# table b;
 id | v
----+---
  1 | b
  2 | b
  1 | b
(3 rows)
​
postgres=# select a.* from a where exists(select 1 from b where a.id = b.id);
 id | v
----+---
  1 | a
  2 | a
(2 rows)
​
postgres=# select a.* from a join b on a.id = b.id ;
 id | v
----+---
  1 | a
  1 | a
  2 | a
(3 rows)
​
postgres=#

转载于:https://my.oschina.net/207miner/blog/3008139

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值