openGauss内核分析(四):查询重写(二)
酷哥 [openGauss](javascript:void(0);) 2022-12-13 18:01 发表于四川
外连接消除Outer2Inner
下面首先以一个例子来说明各种多表连接方式的区别:
create table t1(c1 int, c2 int);
create table t2(c1 int, c2 int);
insert into t1 values(1, 10);
insert into t1 values(2, 20);
insert into t1 values(3, 30);
insert into t2 values(1, 100);
insert into t2 values(3, 300);
insert into t2 values(5, 500);
内连接inner join:返回两个表都满足的组合,相当于取两个表的交集。
SELECT * FROM t1 inner JOIN t2 ON t1.c1 = t2.c1;
左连接 left outer join:返回左表中的所有行,如果左表中行在右表中没有匹配行,则结果中右表中的列返回空值。
SELECT * FROM t1 Left OUTER JOIN t2 ON t1.c1 = t2.c1;
右连接 right outer join:返回右表中的所有行,如果右表中行在左表中没有匹配行,则结果中左表中的列返回空值。
SELECT * FROM t1 right OUTER JOIN t2 ON t1.c1 = t2.c1;
全连接 full join:返回左表和右表中的所有行。当某行在另一表中没有匹配行,则另一表中的列返回空值,相当于取两个表并集。
SELECT * FROM t1 full JOIN t2 ON t1.c1 = t2.c1;
在以上实验的基础上增加t2表的where条件。
left join和inner join的结果是一样的,这是因为查询条件中包含WHERE t2.c2 >100这个条件,t2表所有不匹配元组均被过滤掉(包括空值),因此可以进行查询转换left-outer join -> inner join,能够有效减小t1和t2关联产生的结果集,达到性能提升的目的。
在openGauss数据库系统中,subquery_planner会遍历查询树中的rtable,看看是否有RTE_JOIN类型的节点存在,设置hasOuterJoins标志量,从而进入到reduce_outer_joins接口,满足外连接消除条件时再执行外连接的消除。reduce_outer_Joins函数内部做两个动作:
(1)reduce_outer_joins_pass1预检查,就是检查jointree中是否含有外链接,以及一些引用表的信息,为动作2做好信息采集准备,重点参考数据结构reduce_outer_joins_state;
(2)reduce_outer_joins_pass2真正完成消除外链接。
void reduce_outer_joins(PlannerInfo* root)
{
reduce_outer_joins_state* state = NULL;
state = reduce_outer_joins_pass1((Node*)root->parse->jointree);
/* planner.c shouldn't have called me if no outer joins */
if (state == NULL || !state->contains_outer)
ereport(ERROR,
(errmodule(MOD_OPT),
errcode(ERRCODE_OPTIMIZER_INCONSISTENT_STATE),
(errmsg("so where are the outer joins?"))));
reduce_outer_joins_pass2((Node*)root->parse->jointree, state, root, NULL, NIL, NIL);
}
利用上一期的分析方法,可以得到查询树内存结构(查询树Query结构体中targetList存储目标属性语义分析结果,rtable存储FROM子句生成的范围表,jointree的quals字段存储WHERE子句语义分析的表达式树)
对比reduce_outer_joins运行前后查询树,jointree和rtable中的jointype都由join_left转换为join_inner,即外连接已转为内连接。
(gdb) p *((JoinExpr*)(parse->jointree->fromlist->head.data->ptr_value))
$1 = {type = T_JoinExpr, jointype = JOIN_INNER, isNatural = false, larg = 0x7fdfb345cd08, rarg = 0x7fdfb345e2e8, usingClause = 0x0, quals = 0x7fdfb2f0b8a8, alias = 0x0, rtindex = 3}
(gdb) p *(RangeTblEntry*)(parse->rtable->tail.data->ptr_value)
$2 = {type = T_RangeTblEntry, rtekind = RTE_JOIN, relname = 0x0, partAttrNum = 0x0, relid = 0, partitionOid = 0, isContainPartition = false, subpartitionOid = 0, isContainSubPartition = false,
refSynOid = 0, partid_list = 0x0, relkind = 0 '\000', isResultRel = false, tablesample = 0x0, timecapsule = 0x0, ispartrel = false, ignoreResetRelid = false, subquery = 0x0, security_barrier = false,
jointype = JOIN_INNER, …}