查询折叠指的是把查询中的视图、CTE或是DT子查询展开,并与引用它的查询语句合并,从而减少查询语句的子查询数目,降低其复杂度的一种优化算法。其收益有以下三个方面:
考虑下面的例子,
SELECT * FROM (SELECT c_custkey, c_name FROM customer) AS dt;
重写后的SQL为,
SELECT c_custkey, c_name FROM customer
注1. 在下文中,我们将使用“视图”一词,但所有描述也适用于CTE或是DT子查询。 注2. 本文所使用的执行计划可视化工具为 PawSQL Explain Visualizer , 支持MySQL、PostgreSQL、openGauss等数据库。
PawSQL优化引擎针对不同的SQL语法结构,支持两种查询折叠的优化策略。
将视图拆分并合并到外部查询块中。
select c.c_name, sum(o_totalprice) price
from customer c, (select o_custkey, o_totalprice from orders where o_shippriority=0)dt
where c.c_custkey = dt.o_custkey
group by c.c_name
select c.c_name, sum(o_totalprice) as price
from customer c, orders
where c.c_custkey = o_custkey and o_shippriority=0
group by c.c_name
我们可以看到,原查询的执行计划中有一个物化步骤,通过SQL重写后,消除了此物化步骤。
视图
是唯一的表引用将外部查询合并至视图,并删除外部查询。
select dt.price
from (select c.c_name, sum(o_totalprice) price
from customer c, orders
where c.c_custkey = orders.o_custkey
group by c.c_name) dt
where dt.c_name like '139%';
select sum(o.O_TOTALPRICE)
from customer as c, orders o
where c.c_custkey = o.o_custkey
and c.c_name like '139%'
group by c.c_name
与类型1类似,我们可以看到重写优化后消除了物化步骤,同时性能提升了231.83%。
注3. 其中对于第一种类型,MySQL 5.7以及PostgreSQL 14.0以上的版本都在优化器内部进行了支持;而第二类查询折叠的优化,在最新的MySQL及PostgreSQL版本中都没有支持。
PawSQL专注数据库性能优化的自动化和智能化,支持MySQL,PostgreSQL,Opengauss等,提供的SQL优化产品包括