PostgreSQL 联结方式--hash联结

          hash联结,首先应用WHERE子句中的筛选标准来独立地读取要进行联结的两个表。基于表和索引的统计信息,被确定为返回最小行数的表被完全散列到内存中。这个散列表包含了原表的索引数据行,并被基于将联结键转化为散列值的随机函数载入到散列桶中。只要有足够的内存控件,这个散列值将一直存放在内存中。然而,如果没有足够的内存,散列表将会被写入到临时磁盘空间。
          下一步就是读取另一张较大的表并对联结键应用散列函数。然后利用得到的散列值对已经在内存中的散列表进行探测以寻找匹配的行数据所在的散列桶。每个散列桶都有一个放在其中的数据行列表(通过一个位图来表示)。这个列表用来与探测行进行匹配。如果匹配成功,则返回这一行数据,否则丢弃。较大的表只读取一次,并检查其中的每一行来寻找匹配。hash联结的内层表被多次读取,较大的表是驱动表,因此仅读取一次,而较小的散列表则被探测很多次。

1. 建表和插入测试数据参考:http://blog.csdn.net/luojinbai/article/details/44033729
2. select s.*,c.class_name from student s,class c where s.class_id=c.id;

这个查询将会向下面的伪代码一样来处理结果:

deltermine the smaller row set,or in the case of an outer join,use the outer joined table(根据返回的行数选择内表)

select s.id, s.name, s.class_id from student s 
hash the class_id column and build a hash table
select c.class_name, c.id from class c
hash the id column and probe the hash table
          if match made,check bitmap to confirm row match
          if not match made,discard the row.
首先内(右)表扫描加载到内存HASH表, hash key为JOIN列.
然后外(左)表扫描, 并与内存中的HASH表进行关联, 输出最终结果
3. 执行计划
postgres=# explain(analyze,verbose,buffers) select s.*,c.class_name from student s,class c where s.class_id=c.id;
                                                      QUERY PLAN                                                       
-----------------------------------------------------------------------------------------------------------------------
 Hash Join  (cost=1.23..13.34 rows=384 width=44) (actual time=0.035..0.289 rows=384 loops=1)
   Output: s.id, s.name, s.class_id, c.class_name
   Hash Cond: (s.class_id = c.id) -- HASH join key, c.id
   Buffers: shared hit=4
   ->  Seq Scan on public.student s  (cost=0.00..6.84 rows=384 width=12) (actual time=0.012..0.098 rows=384 loops=1)
         Output: s.id, s.name, s.class_id
         Buffers: shared hit=3
   ->  Hash  (cost=1.10..1.10 rows=10 width=36) (actual time=0.012..0.012 rows=10 loops=1) 
         Output: c.class_name, c.id
         Buckets: 1024  Batches: 1  Memory Usage: 1kB -- 内(右)表加载到内存, hash key是join key c.id, 如果Batches大于1则会用到临时文件
         Buffers: shared hit=1
         ->  Seq Scan on public.class c  (cost=0.00..1.10 rows=10 width=36) (actual time=0.003..0.006 rows=10 loops=1)
               Output: c.class_name, c.id
               Buffers: shared hit=1
 Total runtime: 0.359 ms
(15 rows)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值