本文分享自华为云社区《【SQL优化】为什么有时候无法走执行性能更优的hashjoin》,作者: leapdb。
1. 在session级关闭nestloop方式,set enable_nestloop to off;
CREATE DATABASE test_td WITH DBCOMPATIBILITY='td'; create table dim_day(day_code char(8)); create table dwr_rpo as select current_date - 1 as day_code; --返回了date类型 test_td=# \d+ dwr_rpo Table "public.dwr_rpo" Column | Type | Modifiers | Storage | Stats target | Description ----------+------+-----------+---------+--------------+------------- day_code | date | | plain | | Has OIDs: no Distribute By: ROUND ROBIN Location Nodes: ALL DATANODES Options: orientation=row, compression=no explain select * from dwr_rpo a left join dim_day c on c.day_code = a.day_code; id | operation | E-rows | E-distinct | E-memory | E-width | E-costs ---+----------------------------------------------+---------+------------+----------+---------+-------------- 1 | -> Streaming (type: GATHER) | 1310148 | | | 1694 | 279235196.70 2 | -> Nested Loop Left Join (3, 4) | 1310148 | | 1MB | 1694 | 279229682.93 3 | -> Seq Scan on dwr_rpo a | 1310148 | | 1MB | 1676 | 46589.16 4 | -> Materialize | 109575 | | 16MB | 22 | 3747.76 5 | -> Streaming(type: BROADCAST) | 109575 | | 2MB | 22 | 3565.14 6 | -> Seq Scan on dim_day c | 36525 | | 1MB | 22 | 272.75 Predicate Information (identified by plan id) ----------------------------------------------------------------------------- 2 --Nested Loop Left Join (3, 4) Join Filter: ((c.day_code)::timestamp without time zone = a.day_code)
不同数据类型计算hash函数不同,互不兼容的数据类型无法进行hash比较。
nestloop复杂度:131w * 10w = 1310亿
hashjoin复杂度:131w
看似类型相近,但由于两端的精度,格式,有无时区等不一样,无法认为直接相等。
select oprname,oprkind,oprcanhash, (select typname from pg_type where oid=oprleft) oprleft, (select typname from pg_type where oid=oprright) oprright from pg_operator where oprname='=' and oprcanhash='f'; oprname | oprkind | oprcanhash | oprleft | oprright ---------+---------+------------+---------------+--------------- = | b | f | xid | int8 = | b | f | xid32 | int4 = | b | f | tid | tid = | b | f | box | box = | b | f | path | path = | b | f | tinterval | tinterval = | b | f | money | money = | b | f | circle | circle = | b | f | lseg | lseg = | b | f | line | line = | b | f | bit | bit = | b | f | varbit | varbit = | b | f | date | timestamp = | b | f | date | timestamptz = | b | f | timestamp | date = | b | f | timestamptz | date = | b | f | timestamp | timestamptz = | b | f | timestamptz | timestamp = | b | f | tsvector | tsvector = | b | f | tsquery | tsquery = | b | f | record | record = | b | f | hll | hll = | b | f | hll_hashval | hll_hashval = | b | f | roaringbitmap | roaringbitmap (24 rows)
current_date 在TD兼容模式下为date类型;