更新时间:2025-03-13 GMT+08:00
Cte Scan
算子说明
CTE(Common Table Expression)是一种临时表达式,Cte Scan用于扫描CTE表达式生成的临时表。
在GaussDB中,可以通过使用with关键字来指定一个或多个CTE,然后在后续的查询中多次使用。
典型场景
当一个查询结果集需要在后续的查询中多次使用的时候,可以考虑使用CTE来避免多次计算。
示例
示例:带WITH语句的无法改写为子查询的CTE。
--数据准备。 gaussdb=# CREATE TABLE employees(deptid integer, salary number); CREATE TABLE gaussdb=# CREATE TABLE managers(deptid integer); CREATE TABLE --执行结果。 gaussdb=# EXPLAIN WITH table_b AS (SELECT deptid,sum(salary) dept_salary FROM employees GROUP BY deptid) SELECT m.deptid, b.dept_salary FROM managers m,table_b b,table_b c WHERE m.deptid = b.deptid AND m.deptid = c.deptid; QUERY PLAN -------------------------------------------------------------------------------------------------------------- Hash Join (cost=1.15..1.81 rows=20 width=36) Hash Cond: (c.deptid = m.deptid) CTE table_b -> Data Node Scan on employees "_REMOTE_TABLE_QUERY_" (cost=0.00..0.00 rows=20 width=36) Node/s: All datanodes -> CTE Scan on table_b c (cost=0.00..0.40 rows=20 width=4) -> Hash (cost=0.90..0.90 rows=20 width=40) -> Hash Join (cost=0.25..0.90 rows=20 width=40) Hash Cond: (b.deptid = m.deptid) -> CTE Scan on table_b b (cost=0.00..0.40 rows=20 width=36) -> Hash (cost=0.00..0.00 rows=20 width=4) -> Data Node Scan on managers "_REMOTE_TABLE_QUERY_" (cost=0.00..0.00 rows=20 width=4) Node/s: All datanodes (13 rows) --删除表。 gaussdb=# DROP TABLE employees, managers;
父主题: 表访问方式